Course contentsShow
← Python
Lesson 38 of 1,0601. Foundations and EnvironmentFree lesson

Chaining Logical Operators for Complex Conditions

Combine multiple boolean expressions using logical operators to create sophisticated filtering criteria for data processing and program decision-making.

In this lesson, you will learn how to combine multiple conditions into a single statement to make your programs smarter and more precise.

Up until now, you have used if statements to check a single condition, such as if age > 18:. But what if you need to check two or more conditions at the same time? In Python, you can chain logical operators like and, or, and not to create complex filters.

Combining with and

The and operator requires all conditions to be True. Imagine you are writing a program to grant access to a club. You need the person to be at least 18 years old and have a membership card:

age = 20
has_card = True

if age >= 18 and has_card == True:
    print("Welcome to the club!")

If either condition is False, the code inside the block will not run.

Combining with or

The or operator is more flexible—it only requires at least one of the conditions to be True. For example, perhaps you allow entry if someone is a member or if they have a VIP pass:

is_member = False
has_vip = True

if is_member == True or has_vip == True:
    print("Access granted!")

Using Parentheses for Clarity

When you chain many operators together, it can get confusing. Just like in math, you can use parentheses () to group your logic. Python will evaluate the expressions inside the parentheses first, ensuring your code behaves exactly as you intend:

# Check if the user is an adult AND (has a ticket OR is a staff member)
age = 20
has_ticket = False
is_staff = True

if age >= 18 and (has_ticket == True or is_staff == True):
    print("Welcome inside!")

By chaining these operators, you move from checking simple states to modeling real-world decision-making. You can now build sophisticated filters that look at multiple variables before deciding which path your program should take.

Key Takeaway: Use and when all conditions must be met, or when at least one condition must be met, and parentheses to control the order of evaluation.