Python: input function not working as expected

2020-05-08 08:04发布

Say that the SECRET_NUMBER = 77. I want the function to keep prompting the user until the secret number is guessed. However, the 'your guess is too low' or 'your guess is to high' isn't working properly. If I enter guess_number(4), it says guess is too low, but if I next put in 100, it still says my guess is too low. What might be wrong with my function?

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条回答
一纸荒年 Trace。
2楼-- · 2020-05-08 08:10

input() returns whatever the user entered. You are not storing what the function returns; it is discarded instead.

Store it in your variable:

num = input('Guess a number: ')

You probably want to turn that into an integer; input() returns a string:

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

You only need to ask for it once for each try:

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

Also see Asking the user for input until they give a valid response.

查看更多
【Aperson】
3楼-- · 2020-05-08 08:15

You need to assign the input value to a variable such as

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

Note that I also cast to int because input() returns a string

查看更多
登录 后发表回答