Combining Conditions
Sometimes a single condition isn't enough. You might need to check if a user is both logged in and has permission, or if they're a student or a senior citizen. Python provides logical operators to combine conditions into more complex expressions.
The And Operator
The and operator requires both conditions to be True:
age = 25
has_license = True
if age >= 18 and has_license:
print("Can drive")
This only prints "Can drive" if the person is at least 18 and has a license. If either condition is False, the entire expression is False.
The Or Operator
The or operator requires at least one condition to be True:
age = 70
if age < 13 or age > 65:
print("Discounted ticket")
This prints the message if the person is under 13 or over 65. Only one condition needs to be true for the whole expression to be true.
The Not Operator
The not operator flips a boolean value — True becomes False, and False becomes True:
is_banned = False
if not is_banned:
print("Welcome to the forum")
This is often more readable than checking if is_banned == False.
Combining Multiple Operators
You can combine these operators to build complex logic:
age = 25
is_member = True
has_coupon = False
if is_member and (age >= 18 or has_coupon):
print("Eligible for discount")
Use parentheses to make your intentions clear. Without them, operator precedence rules apply (not first, then and, then or), which can lead to unexpected results.
Practical Examples
Real applications combine conditions constantly:
# Login validation
if username != "" and password != "":
attempt_login()
# Access control
if is_admin or (is_editor and owns_post):
show_edit_button()
# Form validation
if not email_valid or not password_strong:
show_errors()
Keep It Readable
Complex conditions can become hard to follow. When logic gets complicated, consider breaking it into named variables:
is_eligible = age >= 18 and has_id
is_vip = membership_level == "gold"
if is_eligible or is_vip:
grant_access()
This makes your code self-documenting and easier to debug.