Python simple number comparison

前端 未结 2 1176
粉色の甜心
粉色の甜心 2020-12-22 03:22

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

2条回答
  •  醉梦人生
    2020-12-22 03:40

    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"
    

提交回复
热议问题