What is wrong with this Python game code?

import random secret = random.randint (1,99) guess = 0 tries = 0 print ("AHOY! I'm the Dread Pirate Roberts, and I have a secret!") print ("It is a number from 1 to 99. I'll give you 6 tries. ") while guess != secret and tries < 6: guess = input ("What yer guess? ") if guess < secret: print ("Too low, ye scurvy dog") elif guess > secret: print ("Too high, landrubber!") tries = tries + 1 if guess == secret: print ("Avast! Ye got it! Found my secret, ye did!") else: print ("No more guesses! Better luck next time, matey!") print ("The secret number was", secret) 

I keep getting this error: if guess <secret: TypeError: unorderable types: str () <Int ()

+4
source share
3 answers
 guess = input ("What yer guess? ") 

Calling input returns you a string , not an int . When you compare guess with < , you need int to compare the numeric value. Try to do something line by line:

 try: guess = int(input("What yer guess? ")) except ValueError: # Handle bad input 
+12
source

Since Python is strongly typed, you cannot compare string and int. What you got from input() is str not a int . Thus, before the comparison is possible, you need to convert str to int .

 guess = int(input("What yer guess")) 

You should also handle a possible exception if the input is not converted to int . Thus, the code becomes:

 try: guess = int(input("What yer guess")) except ValueError: print ('Arrrrr... I said a number ye lily-livered dog') 

In addition, input() is unsafe, at least in Python 2.x. This is because input() accepts any valid Python statement. You should use raw_input() instead if you are using Python 2.x. If you are using Python 3, just ignore this bit.

 try: guess = int(raw_input("What yer guess")) except ValueError: print 'Arrrrr... I said a number ye lily-livered dog' 
+6
source

You incorrectly produced "landlubber".

A landlord is a person who caresses the earth.
Landlubber is a person who does not know his way around the ship.

And you need to parse your input into int before you can compare it with int.

+1
source

All Articles