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'
Solution 1:
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.
Solution 2:
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
Post a Comment for "Python: Input Function Not Working As Expected"