-6

I'm trying to make a guessing game in python.

from random import randint
print "\nI'm thinking of a number, you have to guess what it is.\n"

num = randint(1,100)
guess = 0

while guess != num:
    guess = raw_input("Guess the number \n")
    if guess < num:
        print "Guess higher next time \n"
    elif guess > num:
        print "Guess lower next time \n"
    elif guess == num:
        print "That's correct \n"

The problem is no matter what number I enter, I keep getting the "guess a lower number" each time. So what's wrong?

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 5
    You have to convert `guess` to an `int`: `guess = int(raw_input("Guess the number n"))`. Otherwise, you're always comparing a string to an int, and the string will always evaluate as "greater than". – dano Nov 04 '14 at 20:05
  • 3
    As for why a string is greater than any number, see here http://stackoverflow.com/a/3270689/3557327 – user3557327 Nov 04 '14 at 20:06
  • 3
    As a side note, this is one of the many things that's better in Python 3.x. If you screw this up, instead of succeeding in a way that makes no sense to you as the author/debugger of the code, it gives you a nice exception that tells you exactly what's wrong. – abarnert Nov 04 '14 at 20:21

1 Answers1

5

With this:

guess = raw_input("Guess the number \n")

guess is a string, not a number.

You can do this:

guess = int(raw_input("Guess the number \n"))

to get an int.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    which will crash the program if it gets bad input ... but +1 all the same since thats really out of the scope of the question – Joran Beasley Nov 04 '14 at 20:10
  • 2
    @JoranBeasley: It won't "crash", it'll raise a `ValueError` saying `invalid literal for int() with base 10: 'your program sucks and you suck'`. Whether you leave that for the user to read, or wrap it in a `try`/`except`, depends on what kind of program you're trying to make for what kind of use case. – abarnert Nov 04 '14 at 20:20
  • 2
    (PS, I'm not trying to say that your users will always try to type in `'your program sucks and you suck'` if you give them a prompt, but my users generally do. :)) – abarnert Nov 04 '14 at 20:22
  • ok fair point ... given the example code and this answer in general terms it will cause his code to fall down ... :P ... but like I said that probably exceeds the scope of the question – Joran Beasley Nov 04 '14 at 20:22