不管我给出什么输入我得到输出"我想你已经老去冒险了。你的冒险在这里结束。" 就像我输入17一样,我得到了#34;我想你已经老去冒险了。你的冒险在这里结束。"如果我输入18-59我会得到"我认为你已经老去冒险了。你的冒险在这里结束。"
while True:
age = raw_input("\n So tell me " + str(name) + ", how old are you?: ")
if age.isdigit() == False:
print "\n Please, put only in numbers!"
time.sleep(3)
elif age < 18:
print "\n %s. A minor. You got to be atleast 18 to go on this adventure. Your adventure ends here." % age
time.sleep(7)
exit(0)
elif age >= 60:
print "\n %s. I think you're to old to go on an adventure. Your adventure ends here." % age
time.sleep(5)
exit(0)
else:
print "\n %s. You're starting to get old." % age
break
答案 0 :(得分:3)
您需要将输入与int
age = int(raw_input("\n So tell me " + str(name) + ", how old are you?: "))
否则,您要将str
与int
进行比较。请参阅以下示例
>>> 5 < 10
True
>>> type(5)
<type 'int'>
>>> '5' < 10
False
>>> type('5')
<type 'str'>
在Python 2.x中,比较不同类型的值通常会忽略这些值并改为比较类型。因为str >= int
,任何字符串都是>=
任何整数。在Python 3.x中,你得到一个TypeError
,而不是默默地做一些令人困惑和难以调试的事情。
答案 1 :(得分:1)
问题是raw_input
总是返回一个字符串对象,而那些并不真正与int
类型进行比较。你需要进行一些类型转换。
如果您想使用isdigit
来测试输入是否为数字,那么您应该采用以下方式:
while True:
age = raw_input("\n So tell me " + str(name) + ", how old are you?: ")
if age.isdigit() == False:
print "\n Please, put only in numbers!"
time.sleep(3)
elif int(age) < 18:
print "\n %s. A minor. You got to be atleast 18 to go on this adventure. Your adventure ends here." % age
time.sleep(7)
exit(0)
elif int(age) >= 60:
print "\n %s. I think you're to old to go on an adventure. Your adventure ends here." % age
time.sleep(5)
exit(0)
else:
print "\n %s. You're starting to get old." % age
break
但是,您可以通过立即转换为整数来简化代码,如果它是无效的字符串,只需捕获异常:
while True:
try:
age = int(raw_input("\n So tell me " + str(name) + ", how old are you?: "))
if age < 18:
print "\n %s. A minor. You got to be atleast 18 to go on this adventure. Your adventure ends here." % age
time.sleep(7)
exit(0)
elif age >= 60:
print "\n %s. I think you're to old to go on an adventure. Your adventure ends here." % age
time.sleep(5)
exit(0)
else:
print "\n %s. You're starting to get old." % age
break
except ValueError:
print "\n Please, put only in numbers!"
time.sleep(3)