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: '))
好的,所以我正在尝试确保用户输入一个整数值。如果我不输入整数,则会出现"输入无效,请输入整数值",然后我将输入另一个非整数值,最终会收到错误消息。那么为什么它第一次有效而不是第二次呢?
当用户输入正确的整数字符串时,使用 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.
顺便说一句,hours != int
总是会产生True
.如果要检查对象的类型,可以使用isinstance
。但正如您在上面的代码中看到的那样,您不需要它。