-1

我试图创建一个猜数游戏,但我收到“guesstaken”的错误我从http://inventwithpython.com/IYOCGwP_book1.pdf第 57 页复制了代码。对不起,我对 python 有点陌生。

import random
guessestaken=0
print ("hello what ur name?")
myname=input()
number=random.randint(1,20)
print ("well " + myname + " i am thinking of a number guess it")

while guessestaken < 6 :
    guessestaken=guessestaken+1
    guess =input('take a guess')
    guess = int(guess)

    if guess <number:
        print('too low')
    if guess >number:
        print ('too high')
    if guess ==number:
        break
    if guess ==number:
        guessestaken=str(guessestaken)
        print ('good job ' + myname + ' you are right!')
        print ('you guessed it in ' + guessestaken + ' guesses')
    if guess !=number:
        guessestaken = str(guessestaken)
        print ("I am sorry but you couldn't get it right")
        print ("you couldn't guess it in " + guessestaken + " guesses")
4

2 回答 2

4

The error message is (trying to) inform you that you're trying to compare a str with an int. In particular, there should be a traceback informing you of where the error occurs:

Traceback (most recent call last):
  File "./tmp.py", line 8, in <module>
    while guessestaken < 6 :

You can see that you explicitly convert guessestaken to a string:

guessestaken = str(guessestaken)

Which is clearly not necessary. When you want to print the number of guesses taken, either do it inline using + (which is not recommended or "pythonic") or use format:

print('you guessed it in ' + str(guessestaken) + ' guesses')
print('You guessed it in {} guesses'.format(guessestaken))
于 2013-09-09T11:06:56.220 回答
3

您正在转换guesstaken为字符串以显示它

guessestaken=str(guessestaken)

然后while循环检查是否

while guessestaken < 6 :

这会导致类型错误(python 无法比较stringint)。您应该简单地为字符串使用其他名称,或者使用 python 结构内联,如

print('You guessed it in {} guesses'.format(guessestaken))
于 2013-09-09T11:06:49.313 回答