Compound Logical Expressions
Sometimes you want to check more than one condition at a time. In Python, you can combine multiple conditions using logical operators:
and
: Both conditions must be true.or
: At least one condition must be true.not
: Inverts the condition.
1. Using and
age = 20
has_id = True
if age >= 18 and has_id:
print("Allowed to enter")
- This prints "Allowed to enter" only if both conditions are true.
2. Using or
is_student = False
has_coupon = True
if is_student or has_coupon:
print("Eligible for discount")
- This prints "Eligible for discount" if either is true.
3. Using not
logged_in = False
if not logged_in:
print("Please log in")
- This prints "Please log in" because
logged_in
is false andnot
flips it.
4. Compound Conditions in Tables
Let's say we want to filter students who:
-
Scored 70 or more
-
AND their name starts with a letter before 'D'
students = [
["Name", "Score"],
["Alice", 85],
["Bob", 59],
["Charlie", 72],
["Diana", 91],
["Eve", 66]
]
filtered = [["Name", "Score"]]
for row in students[1:]:
name = row[0]
score = row[1]
if score >= 70 and name[0] < 'D':
filtered.append(row)
print(filtered)
Output
[['Name', 'Score'], ['Alice', 85'], ['Charlie', 72]]
Exercise: Try It Yourself!
Write a program that filters a list of books and selects only the ones that are:
-
Priced above 30
-
AND the genre is "Science"
books = [ ["Title", "Price", "Genre"], ["Deep Space", 45, "Science"], ["Cooking 101", 25, "Lifestyle"], ["The Quantum Code", 60, "Science"], ["Comfy Living", 35, "Home"] ]
Expected Output
[['Title', 'Price', 'Genre'], ['Deep Space', 45, 'Science'], ['The Quantum Code', 60, 'Science']]