【发布时间】:2016-09-27 18:52:34
【问题描述】:
我是 python 3 的新手,我不明白为什么会出现类型错误(这是一个猜测 0-100 之间数字的数字游戏):
print("Please think of a number between 0 and 100!")
low = 0
high = 100
check = False
while True :
guess = (low + high)/2
print("Enter 'h' to indicate the guess is too high.\n")
print("Enter 'l' to indicate the guess is too low.\n" )
print("Enter 'c' to indicate I guessed correctly.\n")
ans = input("")
if ans == "h" :
low = ans
elif ans == "l" :
high = ans
elif ans =="c" :
print( "Game over. Your secret number was:{}".format(guess))
break
else :
print("Sorry, I did not understand your input.")
这是错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
在此先感谢。非常感谢您的帮助,我陷入了困境
【问题讨论】:
-
你需要放完整的回溯。但是从您的代码中:当用户输入任何内容时,除了
c,它会引发错误,因为您将输入值(str对象)分配给low或high变量然后尝试执行int操作.第一次+然后/2 -
是的,您在条件的前两部分将“low”或“high”更改为字符串。然后当 while 循环重新开始时,它会尝试将它们用作整数来再次计算“猜测”。
-
这不是什么游戏;玩家不是在猜测一个数字,而是根据他们输入的
hs 和ls 的顺序来选择一个数字。
标签: python typeerror traceback