Python 3:回溯:TypeError

时间:2016-09-27 18:52:34

标签: python typeerror traceback

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

先谢谢。我真的很感谢你的帮助我被困在这个

2 个答案:

答案 0 :(得分:0)

low = ans行上,您将低值设置为字符串值,字符串值为&#34; h&#34;

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

每一行向朋友(或软玩具)解释每一行的作用以及为什么你确定每一行都是正确的。

答案 1 :(得分:0)

有几件事。

  1. 您应该打印猜测,以便用户知道它是太高还是太低
  2. low==ans没有任何意义。假设用户遵守规则,ans将是&#34; h&#34;,&#34; l&#34;或&#34; c&#34; lowhigh需要为数字才能正确生成guess
  3. 你的逻辑也是错误的。以下代码有效。

    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.")