2

Are there any special rules in regards to using the != operation in a while statement in python. For example I have a loop of code like this

input("f_l value ")
while f_l != "s" or f_l != "S" or f_l != "q" or f_l != "Q":
    print("Error")
    input("f_l value ")
print("your f_l is correct")

The while loop won't stop and print the value. I don't know why. Any ideas?

Pang
  • 9,564
  • 146
  • 81
  • 122
Casey Gilles
  • 83
  • 3
  • 7

1 Answers1

4

First of all, you're not assigning the return value of input() to f_l, so, how may it contain the required value? You should do something like this:

f_l = input('f_l value')
while f_l != 's' or f_l != 'S' or f_l != 'q' or f_l != 'Q':
    print('Error')
    f_l = input('f_l value')

print('your f_l is correct')

Now, that will still loop forever. Why? Because nothing can be 's', 'S', 'q', and 'Q' at the same time, because that's what you're expressing with the ors as the condition for the loop to finish. Maybe you want to replace them with ands?

while f_l != 's' and f_l != 'S' and f_l != 'q' and f_l != 'Q':

Now, that works, but it's still not optimal. You're checking for every possible input value, rather than simplifing yourself and doing something like:

while f_l.lower() not in ['s', 'q']:
3442
  • 8,248
  • 2
  • 19
  • 41
  • @saulspatz: Eh... That's exactly what I said, no? **Edit**: Sorry, I didn't understood your comment's first sentence. May you clarify it a bit, please? – 3442 Oct 09 '15 at 01:27
  • You're right; I somehow just skipped over that paragraph when I read your answer. Sorry. – saulspatz Oct 09 '15 at 01:34