Python简单数字比较

时间:2013-09-25 16:25:39

标签: python if-statement random comparison

问题:

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

我的解决方案:

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"

不幸的是,我的代码永远不会通过if语句传递,即使我总是打印“你的号码太大”,即使我为用户输入“1”。

2 个答案:

答案 0 :(得分:2)

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"

答案 1 :(得分:1)

您的user变量是字符串类型,因为raw_input()返回字符串,更改您的代码如下:

user = int(raw_input('> '))

所以user将是整数。