简体   繁体   中英

how do I fix this error in python 3.3? TypeError: unorderable types: str() < int()

i was trying to create a number guessing game but I get the error for "guessestaken"I copied the code from http://inventwithpython.com/IYOCGwP_book1.pdf page 57.Sorry I am a bit new to 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")

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))

You are converting guesstaken to string to display it

guessestaken=str(guessestaken)

and then while loop checks whether

while guessestaken < 6 :

which causes type error (python cannot compare string and int ). You should simply use other name for the string or do it inline using python constructs like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM