Reputation: 3
I'm a newbie to Python, and I was working on a number guessing game in Python. However, when I set up the parameters:
import random
numberchosen = random.randint(0,100)
numberchosenstr = str(numberchosen)
print ("Let's play a number game")
numberguessed = input("Guess a number ")
print ("You guessed " + numberguessed)
if numberguessed > '100':
print ("You guessed too high, choose a number below 100")
if numberguessed < '0':
print ("You guessed too low, choose a number above 0")
if numberguessed != numberchosen:
print ("wrong")
But, when I run the module, and choose the number 5 for instance, or any number that is within the correct range yet not the correct number, it always returns
Let's play a number game
Guess a number 5
You guessed 5
You guessed too high, choose a number below 100
wrong
So, my question is, why does Python return the >100 error, and what are some ways to fix it?
Upvotes: 0
Views: 83
Reputation: 23211
You're comparing strings, which is done lexicographically (i.e. alphabetically, one character at a time). But even if one were an int, strings are always greater than numbers. You need to take the quotes off your comparison number, and call int()
on your input
, like so:
numberguessed = int(input("Guess a number ")) # convert to int
print ("You guessed {}".format(numberguessed)) # changed this too, since it would error
if numberguessed > 100: # removed quotes
print ("You guessed too high, choose a number below 100")
if numberguessed < 0: # removed quotes
print ("You guessed too low, choose a number above 0")
Upvotes: 7