hours = 0.0
while hours != int:
try:
hours = int(raw_input('Enter how many hours ahead you want to know the weather: '))
break
except ValueError:
print "Invalid input. Please enter an integer value."
hours = int(raw_input('Enter how many hours ahead you want to know the weather: '))
好的,所以我试图确保用户输入一个整数值。如果我没有输入一个整数"无效输入,请输入一个整数值。"将出现,然后我将输入另一个非整数值,并最终收到错误消息。那么为什么第一次而不是第二次呢?
答案 0 :(得分:4)
当用户输入正确的整数字符串时,使用break
语句退出循环。
hours = 0.0
while True:
try:
hours = int(raw_input('Enter how many hours ahead you want to know the weather: '))
break # <---
except ValueError:
print "Invalid input. Please enter an integer value."
# No need to get input here. If you don't `break`, `.. raw_input ..` will
# be executed again.
BTW,hours != int
总是会产生True
。如果要检查对象的类型,可以使用isinstance
。但正如您在上面的代码中看到的那样,您不需要它。