0
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?

asked Feb 10, 2021 at 3:17
1
  • Do like this > while user not in ['a', 'b', 'c', 'd'] or you can use tuple while user not in ('a', 'b', 'c', 'd') Commented Feb 10, 2021 at 3:24

3 Answers 3

1

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.

answered Feb 10, 2021 at 3:21
Sign up to request clarification or add additional context in comments.

Comments

1

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']:
answered Feb 10, 2021 at 3:25

Comments

0

You can simply use this:

while user not in ["a", "b", "c"]:
 print(user) 
 break
answered Feb 10, 2021 at 3:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.