【问题标题】:Python 3: Traceback : TypeErrorPython 3:回溯:TypeError
【发布时间】: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 对象)分配给lowhigh 变量然后尝试执行int 操作.第一次+ 然后/2
  • 是的,您在条件的前两部分将“low”或“high”更改为字符串。然后当 while 循环重新开始时,它会尝试将它们用作整数来再次计算“猜测”。
  • 这不是什么游戏;玩家不是在猜测一个数字,而是根据他们输入的hs 和ls 的顺序来选择一个数字。

标签: python typeerror traceback


【解决方案1】:

有几件事。

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

【讨论】:

    【解决方案2】:

    low = ans这行你设置low为字符串值,字符串值“h”

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      相关资源
      最近更新 更多