user = input('> ')
while user != ('a' or 'b' or 'c'):
print(user)
break
(I know I should not use 'while' here, but just an example to demonstrate my confusions)
In this code, what I want is: if the user enters 'a' or 'b' or 'c', this 'while loop' will not print out the alphabets. However, there is an error, for 'a', it works fine. But for 'b' and 'c', they still get printed out. May I ask why is that?
-
Do like this > while user not in ['a', 'b', 'c', 'd'] or you can use tuple while user not in ('a', 'b', 'c', 'd')m0r7y– m0r7y2021年02月10日 03:24:35 +00:00Commented Feb 10, 2021 at 3:24
3 Answers 3
You have to break your ('a' or 'b' or 'c') expression:
user = input('> ')
while user != 'a' and user != 'b' and user != 'c':
print(user)
break
When python parses ('a' or 'b' or 'c') it is gonna conclude that 'a' is not null, so it is not necessary to continue the expression in the parenthesis and everything inside became simply 'a'
Or, if you want to keep using your more compact way, your option would be:
user = input('> ')
while user not in ('a', 'b', 'c'):
print(user)
break
In this case, you are looking if you user exists in the tuple.
Comments
You are testing against 3 conditions here.
while user != 'a'
while 'b'
while 'c'
So while user is anything else than 'a', it will print. You could do something like this.
while user != 'a' or user != 'b' or user != 'c':
or
while user not in ['a', 'b', 'c']:
Comments
You can simply use this:
while user not in ["a", "b", "c"]:
print(user)
break