Comparison and Logical Operators
==, <, >, and, or, not.
4 minute read
Big idea
Comparison operators ask a question and answer True or False. Logical operators — and, or, not — combine those answers.
Comparisons
| Operator | Question |
|---|---|
== | equal? |
!= | not equal? |
< > | less / greater? |
<= >= | less-or-equal / greater-or-equal? |
x = 7
print(x == 7)
print(x != 7)
print(x > 10)
print("apple" == "Apple")output
True
False
False
FalseRun and edit it in the app.
String comparison is exact — a capital letter makes it a different string.
= assigns; == compares. Mixing them up is the classic mistake — x = 7 moves x, x == 7 asks about it.
Chained comparisons
Python lets you write a range check the way you would in maths:
age = 15
print(13 <= age <= 19) # True — a teenager
and, or, not
a and b— True only if both are True.a or b— True if at least one is True.not a— flips True and False.
sunny = True
warm = False
print(sunny and warm)
print(sunny or warm)
print(not warm)
print(sunny and not warm)What does it print? Show the answer
False
True
True
TrueRun and edit it in the app.
Short-circuiting
Python stops as soon as it knows the answer. In a and b, if a is False the whole thing is False, so b is never even looked at. That makes this safe:
count = 0
print(count != 0 and 100 / count > 5) # False — the division never runs
Without short-circuiting, 100 / 0 would crash the program.
Watch it
A common slip
color = "green"
is_primary = color == "red" or "blue"
print(bool(is_primary))output
FalseRun and edit it in the app.
color == "red" or "blue" means (color == "red") or ("blue"), and "blue" on its own is a non-empty string — always truthy. Write the comparison out in full both times: color == "red" or color == "blue".
x = 5. What is x > 1 and x < 4 ?
Think of it like
A club door. "Over 18 and has a ticket" — you need both. "Member or on the guest list" — either one gets you in. not flips the bouncer's answer.
Key terms
- Comparison operator —
==,!=,<,>,<=,>=; gives a boolean. - Logical operator —
and,or,not; combines booleans. - Short-circuit — Stopping early once the answer is known.
Check yourself
What's the difference between = and ==?
What is True or False?
What does 1 < 5 < 3 give?