在python中,如何创建一个自定义异常来处理用户输入,并考虑值的范围?

2024-10-02 18:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python,我遇到了以下练习:

Create your own custom exception that will handle user input that is NOT in the appropriate range of values you want them to enter (such as a percentage mark must be 0 and 100) HINT: You will need a definition!

这个措辞让我困惑,但据我所知,我必须创建一个程序,该程序的值必须介于0和100之间,并且必须包含一个异常和一个定义(?)你知道吗

以下是我尝试过的:

mark = 0

class Illegal(Exception):
    pass

while True:
    try:
        uMark = int(input("Enter a mark out of 100 to see if its valid or not: "))
        if 100 < uMark < 0:
            raise Illegal
        break
    except Illegal:
        print("Invalid mark")

print("Valid mark")

然而,这似乎不起作用,因为当我输入200时,它返回Valid mark。你知道吗


Tags: ofto程序inputyourifthatcreate
1条回答
网友
1楼 · 发布于 2024-10-02 18:22:57

这个测试永远不可能是真的:

if 100 < uMark < 0:

链式比较使用来测试所有比较,就像您编写了:

if 100 < uMark and uMark < 0:

整数值不能同时大于100和小于0。你知道吗

您需要显式地使用or

if 100 < uMark or uMark < 0:

现在当uMark太小(低于0)或太大(超过100)时,这个测试将是真的。你知道吗

我会重新安排测试,让人类读者更清楚地知道uMark超出了范围:

if uMark < 0 or 100 < uMark:

相关问题 更多 >