Combining Conditions

Using and, or, and not

8 min read · runnable Python

Sometimes one condition isn't enough. You might need two things to be true at once, or for either of two things to be true. Python gives you three plain-English words for this: and, or, and not.

and — both must be true

age = 25
has_ticket = True
if age >= 18 and has_ticket:
    print("You may enter.")

With and, the whole condition is only true when both parts are true. If either is false, the block is skipped.

or — at least one must be true

day = "Sunday"
if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")

With or, the condition is true when at least one part is true.

not — flips true and false

is_raining = False
if not is_raining:
    print("Let's go for a walk.")

not reverses things: not False becomes true, so the message prints.

About True and False

Those words True and False are special values called booleans (named after George Boole). A comparison like age >= 18 actually produces one of these:

print(10 > 3)    # True
print(10 < 3)    # False

Tip: True and False must be capitalised in Python, with no quotes. true or "True" won't work the same way.

Your turn

Try changing age or has_ticket and see whether the entry message still appears.

Try it yourself
Output
Press “Run code” to see the result.

Quick check

Q1 With if a and b , when does the block run?

Q2 What does not False evaluate to?

Want to save your progress? It's free.

Create a free account