LESSON 10
Logical Operators
One question isn't always enough. Learn to ask several at once.
USES: True/False and comparisons (Lesson 8), if / elif / else (Lesson 9), input( ) and int( ) (Lessons 6 and 7), .lower( ) (Lesson 4).
01
and: both must be true
So far each if asked one question. Real decisions often need two. To get into a concert you need to be 18 or older AND have a ticket. and is only True when both sides are True. Here is the whole rule, printed:
BLUEPRINT · TAP OR HOVER EACH PIECE
Blueprint 1 of 2: the and condition. Tap each piece.
02
or: one is enough
Sometimes either condition is enough. Weekends are Saturday or Sunday. or is False only when both sides are False.
03
The or trap
This next line looks right in English and is wrong in Python. On a Monday it prints Weekend! The reason: or joins two complete conditions, and "Sunday" on its own is not a question. Python treats any text that is not empty as meaning True, so the right side is always True and the whole or always passes. The fix is the full comparison on both sides.
04
not: flip the answer
not turns True into False and False into True. It reads naturally with a True/False variable: if not raining is already English.
05
Mixing them, and the order
You can combine all three in one condition. When you do, Python works out not first, then and, then or. Brackets change the order, exactly like in maths from Lesson 3.
06
Checking a range
In Lesson 8 you saw the chained comparison 13 <= age <= 19. and gives you another way to write the same thing. Use the chained form for a simple range, and and when the two checks are different kinds of things.
07
Putting it all together
Now combine everything, with two answers from the user. Look at the line has_id = answer.lower() == "yes": it is Lesson 8's idea of keeping an answer in a box. The question is asked once, and True or False goes into has_id. Typing YES, yes or Yes all work.
BLUEPRINT · TAP OR HOVER EACH PIECE
Blueprint 2 of 2: turning an answer into a boolean. Tap each piece.
08
Quick quiz: what does this print?
What does print(True and False or True) show?
09
Quick quiz: two lines
x = 15 print(x > 10 and x < 12) print(x > 10 or x < 12) What prints?
10
Quick quiz: which condition is correct?
You want to check whether day is Saturday or Sunday. Which condition is correct?