验证整数的错误消息,如何?

时间:2015-01-27 22:52:14

标签: python validation

我一直在研究需要验证错误消息的睡眠计算器。我需要验证的代码是:

hourspernight = int(input("How many hours do you sleep in a day?")
hoursperweek = hourspernight * 7
input("You Sleep for",hoursperweek,"hours every week!")

我需要添加验证,这样,如果用户输入的字符不是整数,则会显示一条要求输入整数的错误消息。

1 个答案:

答案 0 :(得分:1)

try/except内使用while loop,在用户输入有效内容之前,它会一直询问输入:

while True:
    try:
       hourspernight = int(input("How many hours do you sleep in a day?"))
       break
    except ValueError:
        print("Invalid input")

hoursperweek = hourspernight * 7
print ("You Sleep for {} hours every week!".format(hoursperweek))