Python:输入函数不能按预期工作

时间:2013-06-20 21:04:14

标签: python input python-3.x

假设SECRET_NUMBER = 77.我希望该功能一直提示用户,直到猜到密码。但是,你的猜测太低'或者'你的猜测是高的'没有正常工作。 如果我输入guess_number(4),它表示猜测太低,但如果我接下来输入100,它仍然说我的猜测太低了。我的功能可能有什么问题?

def guess_number(num):

    '''(int) -> NoneType

       Print out whether the secret number was guessed or a hint, if the
       number was not guessed. Make this prompt the user for a number until the
       secret number is guessed.

       >>> guess_number(50)
       Your guess was too low!
    '''
    while num != SECRET_NUMBER:

        if num < SECRET_NUMBER:
            print('Your guess was too low!')
            input('Guess a number: ')

        elif num > SECRET_NUMBER:
            print('Your guess was too high!')
            input('Guess a number: ')

    else:
        print('You guessed it!')

2 个答案:

答案 0 :(得分:3)

input() 返回用户输入的内容。您没有存储函数返回的内容;它被丢弃了。

将其存储在您的变量中:

num = input('Guess a number: ')

您可能希望将其转换为整数; input()返回一个字符串:

num = int(input('Guess a number: '))

每次尝试只需要一次:

while num != SECRET_NUMBER:

    if num < SECRET_NUMBER:
        print('Your guess was too low!')

    elif num > SECRET_NUMBER:
        print('Your guess was too high!')

    num = int(input('Guess a number: '))

else:
    print('You guessed it!')

另见 Asking the user for input until they give a valid response

答案 1 :(得分:1)

您需要将输入值分配给变量,例如

num = int(input('Guess a number: '))

请注意,我也转换为int,因为input()返回一个字符串