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
Every comparison evaluates to a boolean — True or False. > and < are the simplest pair:
print(5 > 3)
print(5 < 3)True False
5 > 3 is True; 5 < 3 is False. Six operators work this way; these two are the on-ramp.
Comparisons shine on variables. >= means at least, and != means not equal to — each still hands back a boolean:
score = 90
target = 100
print(score >= target)
print(score != target)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.
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:
enemy_y = 560
floor = 540
price = 152.4
average = 149.0
print(enemy_y > floor)
print(price > average)
print(price != average)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.
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.