Need help with while loop please


I’m making a quiz on python and at the start I ask if they want to do the quiz. My code continues if they enter yes or no but if they enter an invalid answer I want it to ask the question again. I have tried to create a while loop for that but when you run it, it keeps on continuing even if you say yes or no the second time. How do I fix this?



while answer != "yes" or answer != "no", are you sure that is right? Lets do an invalid input (lets say "x", then we get:

while "x" != "yes" or "x" != "no"

which result in:

while True or True:

True or True is true, so the loop keeps running. Now lets do valid input:

while "yes" != "yes" or "yes" != "no"

which gives:

while False or True

False or True is also true, so again, the loop keeps running. That doesn’t seem right. So you need to change either the conditions or the or keyword needs changing, given its not working


Oh OK. That makes a lot of sense now. I will try to do what you suggested. Thanks for the help!


Is there any way that I could write and else statement with the while loop . When I write:

while else:

an error message shows up. What is the correct way of doing this?


you can do:

while condition:
    # do something
   # do something else

then else clause only runs when loop condition becomes false, not when the loop breaks

what are you trying to achieve?


I wanted the else statement to act as the code for the invalid answer. So if they don’t answer ‘yes’ or ‘no’, the else statement will happen and it will keep on happening until they put in a valid answer.


this should be done using a while loop only. First ask for input, then put a while loop to check if they enter correctly, otherwise use the loop to keep prompting for valid input. You don’t need else here


Oh OK. I understand. Thanks for your help again!


you had it nearly right in your original code, but the while loop conditions wasn’t good. And you might want to move your while loop to earlier in your program. Valid user input before doing anything else


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.