如何在python 3.3中修复此错误? TypeError:unorderable类型:str()< INT()

时间:2013-09-09 11:02:21

标签: python python-3.x

我正在尝试创建一个数字猜谜游戏,但我得到了“guessestaken”的错误我从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")

2 个答案:

答案 0 :(得分:4)

错误消息是(试图)通知您,您正试图将strint进行比较。特别是,应该有一个回溯通知您错误发生的位置:

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

您可以看到您明确地将guessestaken转换为字符串:

guessestaken = str(guessestaken)

显然没有必要。如果要打印所采用的猜测数量,可以使用+(不推荐使用或#34; pythonic&#34;)进行内联,也可以使用format

print('you guessed it in ' + str(guessestaken) + ' guesses')
print('You guessed it in {} guesses'.format(guessestaken))

答案 1 :(得分:3)

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

guessestaken=str(guessestaken)

然后while循环检查是否

while guessestaken < 6 :

导致类型错误(python无法比较字符串 int )。 您应该只使用字符串的其他名称或使用python结构(如

)内联
print('You guessed it in {} guesses'.format(guessestaken))