Python simple number comparison

2019-01-29 03:46发布

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.

2条回答
smile是对你的礼貌
2楼-- · 2019-01-29 04:24

your user variable is string type because raw_input() returns string, change your code like:

user = int(raw_input('> '))

So user would be integer.

查看更多
冷血范
3楼-- · 2019-01-29 04:27

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 "<stdin>", line 1, in <module>
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 "<stdin>", line 1, in <module>
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"
查看更多
登录 后发表回答