我正在学习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
。你知道吗
这个测试永远不可能是真的:
链式比较使用和来测试所有比较,就像您编写了:
整数值不能同时大于100和小于0。你知道吗
您需要显式地使用
or
:现在当
uMark
太小(低于0)或太大(超过100)时,这个测试将是真的。你知道吗我会重新安排测试,让人类读者更清楚地知道
uMark
超出了范围:相关问题 更多 >
编程相关推荐