当用户输入的数字超过100或小于0时​​,如何使错误发生

时间:2015-10-21 22:43:56

标签: python 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 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"

2 个答案:

答案 0 :(得分:1)

您可以手动抛出raise的错误,该错误将被捕获为一般except语句(未指定异常类型)。

答案 1 :(得分:1)

你可以这样实现:

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

有关详细信息,请查看以下答案:Manually raising (throwing) an exception in Python