Learning LibraryCore Coding LibraryTeens

Comparison Operators in Python: the tests behind every if

Behind every decision your code makes is a comparison that evaluates to True or False. Master the six operators and you control the flow.

The big idea

Each comparison operator (==, !=, <, >, <=, >=) takes two values and returns a boolean.

See it in code

1The basics

Every comparison evaluates to a boolean — True or False. > and < are the simplest pair:

python
print(5 > 3)
print(5 < 3)
Run it — each comparison returns a boolean:
True
False

5 > 3 is True; 5 < 3 is False. Six operators work this way; these two are the on-ramp.

2A step further

Comparisons shine on variables. >= means at least, and != means not equal to — each still hands back a boolean:

python
score = 90
target = 100
print(score >= target)
print(score != target)
Run it — two operators tested against live values:
False
True

90 >= 100 is False, and 90 != 100 is True. Give the operators variables and they test live state — exactly what a game or a bot needs.

3In our world

Two checks a game and a trading bot make constantly: has an enemy dropped past the floor, and is a price above its moving average? Comparisons answer both:

python
enemy_y = 560
floor = 540
price = 152.4
average = 149.0

print(enemy_y > floor)
print(price > average)
print(price != average)
Run it — three comparisons, three booleans:
True
True
True

560 > 540, 152.4 > 149.0, and 152.4 != 149.0 are all True. Swap any comparison and its boolean flips — that is the switch an if reads to decide what happens next.

The same idea, everywhere

These six operators are the entire vocabulary of tests: gate a retry with attempts < 3, sort by a <= b, detect a target hash with h == goal. Comparisons work on numbers, on strings (alphabetical order), and more — always handing back a boolean.

Try it yourself

Add print(enemy_y >= floor) and print(price <= average), and predict each result before running. Then compare two strings, like "apple" < "banana", to see how Python orders text.

The common mistake

Assignment versus comparison: = binds a name, == tests equality. Python flags if price = average: as a syntax error, but the subtler trap is == versus is — use == to compare values; is asks whether two names point to the very same object.

What it unlocks

Booleans from comparisons combine under boolean logic and steer conditionals, loops, and every branch your program takes.

Want the simpler version? Read the Kids version →