3

我正在用 Python 3 为“猜我的数字”游戏编写代码。然而,在这个版本中,计算机必须猜测用户保密的数字。我是 Python 和一般编程的新手,希望能得到一些帮助。我收到与类型转换有关的错误。这是错误:

    Traceback (most recent call last):
  File "C:\Users\Documents\python\GuessMyNumberComputer.py", line 16, in <module>
    response = input("Is the number" +guess +"? \n Press (y - yes, l - go lower, h - go higher)")
**TypeError: Can't convert 'int' object to str implicitly**

这是我的代码:

 import random

print("\t\t\t Guess My Number")
input("Think of a number between 1 and 100 and I will try to guess it. \nPress enter when you have thought of your number and are ready to begin.")
a = 1
b = 100
tries = 0

while 1==1:
    guess = random.randint(a,b)
    response = input("Is the number" +guess +"? \n Press (y - yes, l - go lower, h - go higher)")
    tries += 1
    if response == y:
        break

    elif response == l:
        b = response-1

    elif response == h:
        a = response+1


print("Aha! I guessed it! And it only took",tries,"tries!")
input("Press enter to exit.")                 

有人可以帮我解决这个错误吗?您能否还给我指出网络上的一些链接,以便我可以阅读此内容,因为我的书似乎没有涵盖该领域。

谢谢。

4

3 回答 3

3

只需将 int 传递给str()构造函数即可将其转换为字符串。所以这是新行:

response = input("Is the number" + str(guess) +"? \n Press (y - yes, l - go lower, h - go higher)")
于 2012-12-10T03:57:59.143 回答
0

其他答案已经解决了您的问题TypeError,因此我将添加一些内容供您阅读:

Python 3.3 教程

于 2012-12-10T04:06:38.417 回答
0

您应该format()在从不同类型构造字符串时使用。它使您的意图更加清晰。

response = input('Is the number {}? \n Press...'.format(guess))
于 2012-12-10T04:03:25.267 回答