Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python while loop condition check for string

In Codeacademy, I ran this simple python program:

choice = raw_input('Enjoying the course? (y/n)')

while choice != 'y' or choice != 'Y' or choice != 'N' or choice != 'n':  # Fill in the condition (before the colon)
    choice = raw_input("Sorry, I didn't catch that. Enter again: ")

I entered y at the console but the loop never exited

So I did it in a different way

choice = raw_input('Enjoying the course? (y/n)')

while True:  # Fill in the condition (before the colon)
    if choice == 'y' or choice == 'Y' or choice == 'N' or choice == 'n':
        break
    choice = raw_input("Sorry, I didn't catch that. Enter again: ")

and this seems to work. No clue as to why

like image 407
Master_Roshy Avatar asked Jul 22 '15 14:07

Master_Roshy


People also ask

How do you check if a string is in a while loop in Python?

Python while loop string condition In this example, while is followed by the variable 'name'. Here we can see if the variable 'name' is set to the string “name”. Here we can check, if the user inputs the string “name”, then the loop will stop and the code will execute outside of the loop.

Do while loops work with strings?

A while loop can be used with the String indexOf method to find certain characters in a string and process them, usually using the substring method. String s = "example"; int i = 0; // while there is an a in s while (s.

Can you use while loops with strings in Python?

Example traversal through a string with a loop in PythonWhile loop will run until a condition is true, so when i is equal to the length of the string, the condition is false, and the body of the loop is not executed.

How do you know if a condition is in a while loop?

While Loops. The concept behind a while loop is simple: While a condition is true -> Run my commands. The while loop will check the condition every time, and if it returns "true" it will execute the instructions within the loop.


1 Answers

You have your logic inverted. Use and instead:

while choice != 'y' and choice != 'Y' and choice != 'N' and choice != 'n':

By using or, typing in Y means choice != 'y' is true, so the other or options no longer matter. or means one of the options must be true, and for any given value of choice, there is always at least one of your != tests that is going to be true.

You could save yourself some typing work by using choice.lower() and test only against y and n, and then use membership testing:

while choice.lower() not in {'n', 'y'}:
like image 131
Martijn Pieters Avatar answered Sep 29 '22 08:09

Martijn Pieters