gpt4 book ai didi

python - 'Guess my number' 游戏类型转换错误

转载 作者:行者123 更新时间:2023-11-28 16:45:54 25 4
gpt4 key购买 nike

我正在用 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.")

有人可以帮我解决这个错误吗?你能不能给我指点网上的一些链接,这样我就可以继续阅读了,因为我的书似乎没有涵盖这个领域。

谢谢。

最佳答案

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

response = input("Is the number" + str(guess) +"? \n Press (y - yes, l - go lower, h - go higher)")

关于python - 'Guess my number' 游戏类型转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13794777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com