Python 当用户输入的数字大于100或小于0时,如何使其发生错误
嘿,有人知道使用Except命令需要使用什么错误处理吗?谢谢,这是我正在尝试使用的代码Python 当用户输入的数字大于100或小于0时,如何使其发生错误,python,except,Python,Except,嘿,有人知道使用Except命令需要使用什么错误处理吗?谢谢,这是我正在尝试使用的代码 try: #Get average, amount earned school_average = input("Enter your average in school:") money_earned = input("How much money did you earn before summer: ") #determine the resulting vacation if
try:
#Get average, amount earned
school_average = input("Enter your average in school:")
money_earned = input("How much money did you earn before summer: ")
#determine the resulting vacation
if school_average >= 80 and money_earned >= 500:
print "You get to go to Europe!"
elif school_average >= 80:
print "You get to go to California."
else:
print "You do not get to go away."
except NameError:
print "Please input a number for your average and amount of money earned."
except:
print "An error has occurred"
您可以使用
raise
手动抛出一个错误,该错误将被捕获为一般语句,但
语句除外(未指定异常类型)。您可以这样实现它:
n = int(input("What is it?\n"))
if 100 > n and n > 0:
print("you did good")
else:
raise ValueError('it must be between 0 and 100')
如果答案大于100或小于0,则会引发ValueError
执行选项:
What is it?
101
Traceback (most recent call last):
File "C:/Users/Leb/Desktop/Python/test2.py", line 6, in <module>
raise ValueError('it must be between 0 and 100')
ValueError: it must be between 0 and 100
这是什么?
101
回溯(最近一次呼叫最后一次):
文件“C:/Users/Leb/Desktop/Python/test2.py”,第6行,在
raise VALUERROR('它必须介于0和100'之间)
ValueError:它必须介于0和100之间
有关更多详细信息,请查看以下答案:实际上,该命令是什么?NameError还是ValueError?