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
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.
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.
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.
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.
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'}:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With