繁体   English   中英

Python 3:回溯:类型错误

[英]Python 3: Traceback : TypeError

我是 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>

提前致谢。我真的很感谢你的帮助我被困在这

几件事。

  1. 您可能应该打印猜测,以便用户知道它是太高还是太低
  2. low==ans没有任何意义。 ans将是“h”、“l”或“c​​”,假设用户遵守规则。 lowhigh需要是数字,以便适当地生成guess

另外你的逻辑不正确。 下面的代码有效。

print("Please think of a number between 0 and 100!")
low = 0
high = 100
check = False
while True:
    guess = (low + high)/2
    print("My guess is: %i" % guess)
    ans = input("Enter 'h' if guess it too high, 'l' if too low, or 'c' if correct: ")
    print(ans)
    if ans == "h":
        high = guess
    elif ans == "l":
        low = guess
    elif ans == "c":
        print("Game over. Your secret number was:{}".format(guess))
        break
    else:
        print("Sorry, I did not understand your input.")

low = ans您将 low 设置为字符串值,字符串值“h”

然后在第二次通过循环时,您尝试计算(low + high )/2` 您无法计算 ("h" + 100)/2 因为您无法将字符串添加到整数。 这是一个“类型错误”

对于每行,向朋友(或毛绒玩具)解释每行的作用以及您确定每行正确的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM