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 keep guessing until you guess the number.
My solution:
import random
computer = random.randint(1, 500)
def guessNumber():
user = raw_input('> ')
while user != computer:
if user > computer:
print "Your number is too big"
user = raw_input('> ')
else:
print "Naa! too small. Try a bit higher number"
user = raw_input('> ')
print "Now the numbers are equal"
Unfortunately, my code never run pass the if statement and even with that that it always prints "Your number is too big" even if I enter '1' for user.
your
user
variable is string type becauseraw_input()
returns string, change your code like:So
user
would be integer.raw_input()
returns a string value. Turn it into an integer first:Since Python 2 sorts numbers before strings, always, your
user > computer
test will always return True, no matter what was entered:Python 3 rectifies this:
Note that if the user does not enter a valid number,
int()
will throw aValueError
:You may want to explicitly handle that: