The problem:
The computer randomly generates a number. The user inputs a number, and the computer will tell you if you are too high, or too low. Then you will get to
raw_input()
returns a string value. Turn it into an integer first:
user = int(raw_input('> '))
Since Python 2 sorts numbers before strings, always, your user > computer
test will always return True, no matter what was entered:
>>> '' > 0
True
Python 3 rectifies this:
>>> '' > 0
Traceback (most recent call last):
File "", line 1, in
TypeError: unorderable types: str() > int()
Note that if the user does not enter a valid number, int()
will throw a ValueError
:
>>> int('42')
42
>>> int('fortytwo')
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: 'fortytwo'
You may want to explicitly handle that:
def askForNumber():
while True:
try:
return int(raw_input('> '))
except ValueError:
print "Not a number, please try again"
def guessNumber():
user = askForNumber()
while user != computer:
if user > computer:
print "Your number is too big"
user = askForNumber()
else:
print "Naa! too small. Try a bit higher number"
user = askForNumber()
print "Now the numbers are equal"