user6514096 user6514096 - 5 months ago 6
Python Question

Looping a program with "while" statement

So, I have this program where you have to guess a number and I've coded it so that the program will tell you if the number you guessed was above or below the true number. My issue is that the program ends after it tells the user to guess higher or lower. I want the program to loop such that the program won't end until the number that I preset is guessed.This is my code:

number = 10
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
elif guess < number:
print ("The number is higher")
else:
print ("The number is lower")
while guess!= number:
print ("Try Again")
print ("Done")


I tried to use a while loop to loop the program until the number was correctly guessed, but the "Try Again" script was looped forever... Thanks for the help!

Answer

while loops don't work that way. It looks like you're expecting some kind of goto where it guesses what you would like it to repeat, but all it will repeat is the content of the block. When it gets to while guess != number:, which is true, it will print that phrase, then check whether guess is not equal to number, which will still be true because it hasn't changed, forever.

Put everything that needs to be repeated into the loop:

number = 10
guess = int(input("Type in an integer: "))
while guess != number:
    if guess < number:
        print ("The number is higher")
    else:
        print ("The number is lower")
    guess = int(input("Type in an integer: "))
print ("Good Job!")
print ("Done") 
Comments