I am running a while loop for a ‘guess the random number’ project. My problem is that when the user is finally guessing the right answer, the code below is not printing ‘Bingo’ as it should. Instead, it is exiting the while loop.
In other languages, the while loop evaluates the conditional after it has run each time. In this case, it appears that the loop is terminating the moment when the conditional is no longer true, even before the last statement has been executed.
Why is this so?
import random
x=100
random_number = random.randint(1,x)
y = int(input('what do you think is the number?! '))
while y!= random_number:
if y>random_number:
print('Too high')
y = int(input('what do you think is the number?! '))
elif y<random_number:
print('Too low')
y = int(input('what do you think is the number?! '))
else:
print('Bingo!')
1
When the user enters the correct number, the y != random_number
condition on the next iteration fails, so the loop stops. It never gets to the else:
block.
Instead of while condition:
, check the condition inside the loop and use break
to stop after printing the message.
while True:
y = int(input('what do you think is the number?! '))
if y>random_number:
print('Too high')
elif y<random_number:
print('Too low')
else:
print('Bingo!')
break