0

假设 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!')
4

2 回答 2

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!')

另请参阅询问用户输入直到他们给出有效响应

于 2013-06-20T21:05:25.520 回答
1

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

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

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

于 2013-06-20T21:05:34.907 回答