Variables & Data Lesson 10 of 23
Python Comparison and Logical Operators
Compare values with ==, !=, >, <, >= and <=, combine conditions with and, or and not, check membership with in, and chain comparisons like 80 <= grade <= 89.
Decisions in programs start with questions that have a yes-or-no answer. Is the grade passing? Is the store open? Is this name on the list? Python answers these with comparison and logical operators, and the answer is always True or False.
Comparison operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 90 > 75 | True |
< | Less than | 60 < 75 | True |
>= | Greater than or equal | 75 >= 75 | True |
<= | Less than or equal | 80 <= 75 | False |
grade = 82
print(grade >= 75)
print(grade == 100)
print("Ana" == "ana")
Output
True False False
String comparison is case-sensitive: "Ana" and "ana" are different.
Logical operators
Python uses plain English words:
| Operator | True when… | Example |
|---|---|---|
and | both sides are true | avg >= 90 and lowest >= 85 |
or | at least one side is true | age >= 60 or is_pwd |
not | flips true/false | not is_closed |
average = 92
lowest = 86
with_honors = average >= 90 and lowest >= 85
print("With honors:", with_honors)
age = 67
is_pwd = False
print("Discount:", age >= 60 or is_pwd)
is_raining = True
print("Can play outside:", not is_raining)
Output
With honors: True Discount: True Can play outside: False
Chained comparisons
Python lets you write ranges just like in math, which most languages don't allow:
grade = 86
print(85 <= grade <= 89) # same as 85 <= grade and grade <= 89
Output
True
Membership: in and not in
officers = ["Ana", "Ben", "Carla"]
print("Ben" in officers)
print("Dan" not in officers)
vowels = "aeiou"
print("e" in vowels)
Output
True True True
Identity: is
is checks if two names refer to the same object. Use it mainly to check for None:
winner = None
print(winner is None)
Output
True
For comparing values like numbers and strings, always use ==, not is.
Order of evaluation
not is evaluated first, then and, then or. Use parentheses to make your meaning clear:
is_member = True
has_coupon = False
total = 600
# Free delivery for members with orders over 500, or anyone with a coupon
free = (is_member and total > 500) or has_coupon
print("Free delivery:", free)
Output
Free delivery: True
Short-circuit evaluation
Python stops checking as soon as it knows the answer. In a and b, if a is false, b is never checked. This lets you write safe checks:
count = 0
total = 100
if count != 0 and total / count > 10:
print("High average")
else:
print("No items yet")
Output
No items yet
Because count != 0 is false, Python never computes total / count, which would have crashed with a division-by-zero error.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04