我正在使用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.")
有人可以帮我解决这个错误吗?你能否指点我网上的一些链接,所以我可以读一读,因为我的书似乎没有涵盖这个领域。
感谢。
答案 0 :(得分:3)
只需将int传递给str()
构造函数即可将其转换为字符串。所以这是新的一行:
response = input("Is the number" + str(guess) +"? \n Press (y - yes, l - go lower, h - go higher)")
答案 1 :(得分:0)
在构造不同类型的字符串时,您应该使用format()
。它使你的意图更清晰。
response = input('Is the number {}? \n Press...'.format(guess))
答案 2 :(得分:0)
其他答案已经解决了您的TypeError
,所以我会为您添加一些内容供您阅读: