Traceback(most recent call last): error
本问题已经有最佳答案,请猛点这里访问。
我对python还不熟悉,我正在编写一个练习脚本,它生成一个介于1和20之间的随机数,要求您猜测该数字,直到正确为止,然后在正确之后打印猜测的数量。代码在我得到最后一个号码之前都有效,然后我得到这个错误:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 |
这是密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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() |
号
有人能解释发生了什么以及如何防止这种情况发生吗?谢谢!
您需要将int转换为字符串,可以使用
失败的原因是因为python不知道如何向文本中添加数字,所以如果您告诉python给您数字的文本版本,那么您可以将它加入到文本中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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() |
号
您需要将您的
1 | str(tries) |
新代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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() |
号
编辑正如评论中所提到的,这也是可行的。
1 | print("Good job! You guessed my number in" , tries) |