Combining Conditions: and, or, not

and – both must be True

age = 25
has_ticket = True
if age >= 18 and has_ticket:
    print("Welcome to the concert!")

Output

Welcome to the concert!

or – at least one must be True

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

Output

It's the weekend!

not – flips True and False

is_logged_in = False
if not is_logged_in:
    print("Please log in first.")

Output

Please log in first.
ExpressionResult
True and TrueTrue
True and FalseFalse
True or FalseTrue
False or FalseFalse
not TrueFalse

Checking a range

Python lets you chain comparisons, which reads just like maths:

score = 65
if 50 <= score <= 100:
    print("You passed")

Output

You passed

Decisions inside decisions

You can put an if inside another if. Each level adds 4 more spaces:

username = "admin"
password = "1234"
if username == "admin":
    if password == "1234":
        print("Access granted")
    else:
        print("Wrong password")
else:
    print("Unknown user")

Output

Access granted

Common mistake: if day == "Saturday" or "Sunday": is always True! Each side of or must be a full comparison: day == "Saturday" or day == "Sunday".

Tip: Real security tip: never write real passwords in your code like the example above. It's only to show nesting.

HOME LEARN COMMUNITY DASHBOARD