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's 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开发者_运维百科()
guess = input ("What's yer guess? ")
Calling input
gives you back a string
, not an int
. When you then compare guess
using <
, you need an int
in order to compare a numerical value. Try doing something along the lines of:
try:
guess = int(input("What's yer guess? "))
except ValueError:
# Handle bad input
Because Python is strongly typed, you can't compare string and an int. What you get back from input()
is a str
not an int
. So, you need to convert the str
to an int
before comparison is possible.
guess = int(input("What's yer guess"))
You should also handle the possible exception thrown when the input is not convertable to an int
. So, the code becomes:
try:
guess = int(input("What's 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're using Python 2.x. If you're using Python 3, just disregard this bit.
try:
guess = int(raw_input("What's yer guess"))
except ValueError:
print 'Arrrrr... I said a number ye lily-livered dog'
You spelled "landlubber" wrong.
A landrubber is a person who caresses the ground.
A landlubber is a person who doesn't know their way around a ship.
And you need to parse your input to an int before you can compare it to an int.
精彩评论