It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

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 and not 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']]