小编典典

Python简单数字比较

python

问题:

计算机随机生成一个数字。用户输入一个数字,然后计算机会告诉您您是否太高或太低。然后,您将继续猜测,直到猜出数字为止。

我的解决方案:

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"

不幸的是,即使我为用户输入“ 1”,我的代码也永远不会运行if语句,即使它始终显示“您的数字太大”。


阅读 246

收藏
2021-01-20

共1个答案

小编典典

raw_input()返回一个 字符串 值。首先将其转换为整数:

user = int(raw_input('> '))

由于Python 2总是在字符串之前对数字进行排序user > computer,因此无论输入什么,您的测试将始终返回True:

>>> '' > 0
True

Python 3纠正了这个问题:

>>> '' > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

请注意,如果用户输入的数字无效,int()则会抛出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'

您可能要明确处理:

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"
2021-01-20