How can I check for two conditions at once?


#1

Question

How can I check for two conditions at once?

Answer

If we want two things to be True before entering a loop, we can use the and operator. Recall that and requires both sides to be True for the entire condition to be True, otherwise it is False.
We’d write condition_1 and condition_2, where condition_1 is the choice not being "y", and condition_2 is the choice not being "n",


FAQ: Learn Python- Loops - Simple errors
#2

But why is there an “and” operator needed in that exercise?
https://www.codecademy.com/courses/learn-python/lessons/loops/exercises/simple-errors?action=resume_content_item
Wouldn’t a logical “and” not insist that both answers are true? Like ‘y’ and ‘n’ would mean that there have to be a ‘y’ AND an ‘n’. I am a bit confused :confused:


#3

yes, but you check if the user input does not equal y and n

if the user enters something invalid (like x), both condition are true, True and True is true, so the loop will run again. Which should happen, given we need to get new input

if the user enters valid input (for example y) one of the conditions is True while the other is False. True and False is false, so the loop stops (which it should, we have valid input)

on the other hand, using or will always result in true (True or True, True or False both evaluate to true), so the loop will keep running forever


#4

Because if you press “y”, you are not pressing “n”… so it will result to an error


#5

Hey guys, thank you very much for your rapid answers.
Now I noticed the failure in my thinking.
Best Regards


#6

Why cant the “or” be used here?

like choice != ‘y’ or ‘n’


#7

that is even worse, 'n' isn’t compared to anything, so python will simple see if 'n' evaluate to true, which it does:

if 'n':
   print True

strings are evaluated as true.


#8

okay this makes sense why I messed up now. its not doing the “choice !=” on the other side of the “or”. It needs something to check on that side as well.


#9

yes, and you should use and not or. But i already explained that