Learning LibraryCore Coding LibraryTeens

Comparison operators in Python: the test behind every rule

"Orders of $75 or more ship free." That sentence becomes one comparison in code, and choosing between > and >= decides whether a $75 order pays for shipping.

The big idea

A comparison evaluates to True or False: ==, !=, <, >, <=, >=.

See it in code

1The basics

Each operator asks one question about two values and answers with a boolean:

python
order_total = 90
free_shipping_min = 75

print(order_total > free_shipping_min)
print(order_total == free_shipping_min)
print(order_total != free_shipping_min)
print(order_total <= free_shipping_min)
Run it. Four questions about one order:
True
False
True
False

A $90 order is greater than 75, not equal to it, and not less than or equal to it. Four operators, four booleans.

2A step further

The interesting case is the boundary. > and >= agree everywhere except when the two values are equal:

python
order_total = 75
free_shipping_min = 75

print("Using > :", order_total > free_shipping_min)
print("Using >=:", order_total >= free_shipping_min)
Run it. An order of exactly $75:
Using > : False
Using >=: True

The policy says "$75 or more", which includes 75. Only >= matches it. With >, a customer who spent exactly $75 gets charged, and the code quietly disagrees with the website.

3At Evergreen

Python lets you chain comparisons, which reads like the math you'd write on paper. This picks out the middle shipping tier:

python
reduced_min = 40
free_shipping_min = 75

for order_total in [30, 40, 60, 75]:
    in_band = reduced_min <= order_total < free_shipping_min
    print(order_total, in_band)
Run it. Is each order in the reduced-shipping band?
30 False
40 True
60 True
75 False

reduced_min <= order_total < free_shipping_min is true from 40 up to, but not including, 75. The two different operators put each boundary on the correct side.

The same idea, everywhere

Boundary choices appear wherever code turns a written rule into a test: a passing score, a reorder point, a price crossing its average. The edge case is where the rule is really decided.

Try it yourself

Change the loop's list to [39.99, 40, 74.99, 75] and predict each answer before running it. Then swap < for <= and see which single result changes.

The common mistake

Confusing = with ==. One binds a name, the other tests equality. Python rejects if order_total = 75: as a syntax error, which is a mercy; the quieter bug is the wrong boundary operator.

What it unlocks

Comparisons are the conditions inside if / elif / else, and and, or, not combine several into one rule.

Want the simpler version? Read the Kids version →