Comparison and boolean operators

Comparison operators

a == b   # equal
a != b   # not equal
a > b    # greater than
a < b    # less than
a >= b   # greater than or equal
a <= b   # less than or equal

The most common beginner mistake: = assigns a value, == compares two values. if x = 5: is a syntax error in Python (unlike some languages, it won't silently do the wrong thing) — you always want if x == 5:.

Chained comparisons

Python lets you chain comparisons the way you would in math class:

if 0 <= score <= 100:
    print("valid score")

That's equivalent to 0 <= score and score <= 100, just more readable.

Boolean operators: and / or / not

and   # True only if both sides are True
or    # True if at least one side is True
not   # flips True to False and vice versa
age = 25
has_ticket = True

if age >= 18 and has_ticket:
    print("can enter")

if age < 13 or age > 65:
    print("discount eligible")

if not has_ticket:
    print("buy a ticket first")

Short-circuiting

and/or stop evaluating as soon as the answer is determined. In a and b, if a is False, Python never even looks at b — the whole expression is already False. This is more than an optimization; it's often used deliberately to avoid errors:

# safe: if the list is empty, "nums and ..." short-circuits before
# ever touching nums[0], avoiding an IndexError
if nums and nums[0] > 10:
    print("first element is big")

Truthiness

Every value in Python is either "truthy" or "falsy" when used in a boolean context. 0, 0.0, "" (empty string), [] (empty list), {} (empty dict), and None are all falsy — everything else is truthy. That means if some_list: is a common, idiomatic way to check "is this list non-empty?" without writing if len(some_list) > 0:.

You now have the full toolkit for writing conditions — time to put it to work.