我是python的新手,我正在编写一个练习脚本,生成一个介于1到20之间的随机数,要求你猜出这个数字,直到你做对了,然后一旦你做对了就输出猜测量。代码一直有效,直到我得到最后一个数字然后我得到这个错误:
Traceback (most recent call last):
File "C:\Users\James Brown\Desktop\guessnumber.py", line 20, in <module>
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 17, in guess
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 17, in guess
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 17, in guess
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 17, in guess
guess()
File "C:\Users\James Brown\Desktop\guessnumber.py", line 18, in guess
print("Good job! You guessed my number in " + tries)
TypeError: Can't convert 'int' object to str implicitly
继承代码
import random
number = random.randint(1,20)
tries = 0
print ("I am thinking of a number between 1 and 20")
def guess():
print (number)
global tries
myGuess = int(input("Take a guess. "))
while (myGuess != number):
if (myGuess > number):
print ("Your guess is too high.")
else:
print ("Your guess is too low.")
tries = tries+1
guess()
print("Good job! You guessed my number in " + tries)
guess()
有人可以解释发生了什么以及如何防止这种情况发生?谢谢!
答案 0 :(得分:1)
您需要将int tries
转换为字符串:
str(tries)
新代码:
import random
number = random.randint(1,20)
tries = 0
print ("I am thinking of a number between 1 and 20")
def guess():
print (number)
global tries
myGuess = int(input("Take a guess. "))
while (myGuess != number):
if (myGuess > number):
print ("Your guess is too high.")
else:
print ("Your guess is too low.")
tries = tries+1
guess()
print("Good job! You guessed my number in " + str(tries))
guess()
修改强>
正如评论中所提到的,这也有效。 print
函数将隐式转换为您。
print("Good job! You guessed my number in " , tries)
答案 1 :(得分:1)
您需要将int转换为字符串,您可以使用str()
函数进行转换。
它失败的原因是因为Python不知道如何向文本添加数字,所以如果你告诉Python给你一个文本版本的数字,那么你可以将它加入到文本中。
import random
number = random.randint(1,20)
tries = 0
print ("I am thinking of a number between 1 and 20")
def guess():
print (number)
global tries
myGuess = int(input("Take a guess. "))
while (myGuess != number):
if (myGuess > number):
print ("Your guess is too high.")
else:
print ("Your guess is too low.")
tries = tries+1
guess()
print("Good job! You guessed my number in " + str(tries))
guess()