Home > Mobile >  Why is my while loop with if statements not working?
Why is my while loop with if statements not working?

Time:10-14

answer = "8"

print("What is 5   3 = ? ")
answer = input()

while (answer != "8"):
  if (answer == "8"):
    print("Correct answer!")
  else:
    print("Incorrect answer!")

Whenever I write the correct answer in the input, the print statement doesn't appear, whereas if I write the incorrect answer, it sends me an infinite amount of my else statement. How can I fix this?

CodePudding user response:

The while loop is executing once for every time that answer != "8". So if you enter 8, it never executes because 8 always equals 8, and if you enter something else, then it executes an infinite number of times because something that does not equal 8 never equals 8. The solution here is to get rid of the while line.

CodePudding user response:

You should move the input method inside the loop - you want the user to be able to input a new number in case the answer is wrong

Working code:

print("What is 5   3 = ? ")
while True:
    answer = input()
    if (answer == "8"):
        print("Correct answer!")
        break
    else:
        print("Incorrect answer!") 

CodePudding user response:

thats because the wile don't execute if the answer is "8". You should Know as weel that every while loop should have a break statement . if you want this code to just print if the result is correct or no you can just delete the while statement

  • Related