我一直在研究需要验证错误消息的睡眠计算器。我需要验证的代码是:
hourspernight = int(input("How many hours do you sleep in a day?")
hoursperweek = hourspernight * 7
input("You Sleep for",hoursperweek,"hours every week!")
我需要添加验证,这样,如果用户输入的字符不是整数,则会显示一条要求输入整数的错误消息。
答案 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))