user2489861
user2489861

Reputation: 109

Python: input function not working as expected

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

Upvotes: 0

Views: 4016

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121406

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.

Upvotes: 3

Dave Lasley
Dave Lasley

Reputation: 6242

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

Upvotes: 1

Related Questions