🎯 Learning Objectives
After completing this section, you will understand:
- How to use logical operators (and, or, not)
- How to combine multiple conditions
- The order of operations in logical expressions
- Common patterns with combined conditions
⚡ Prerequisites
- Understanding of basic conditions
- Knowledge of if statements
- Basic comparison operators
1. Logical Operators
Python provides three logical operators to combine conditions:
Basic Logical Operators
and: True if both conditions are True
or: True if at least one condition is True
not: Inverts the condition (True becomes False)
# Using and
age = 25
income = 50000
if age >= 21 and income >= 40000:
print("Loan approved")
# Using or
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
# Using not
is_working = False
if not is_working:
print("Time to relax")
2. Combining Conditions
You can combine multiple conditions to create complex logical expressions:
# Multiple conditions
age = 25
has_license = True
has_insurance = True
if age >= 18 and has_license and has_insurance:
print("You can rent a car")
# Mixing and/or
is_sunny = True
temperature = 75
is_weekend = True
if (is_sunny and temperature > 70) or is_weekend:
print("Let's go to the beach!")
Tips for combining conditions:
- Use parentheses to make the logic clear
- Break complex conditions into smaller parts
- Test each part separately first
3. Order of Operations
Logical operators have a specific order of evaluation:
Operator Precedence
not (highest precedence)
and
or (lowest precedence)
# Order matters
x = 5
y = 10
z = 15
# These are different:
if x < y and y < z: # Evaluated as: (x < y) and (y < z)
print("Numbers in order")
if not x > y or z > y: # Evaluated as: (not (x > y)) or (z > y)
print("At least one condition is true")
4. Common Patterns
Here are some common patterns when combining conditions:
Range Checks
# Check if number is in range
number = 75
if number >= 0 and number <= 100:
print("Valid percentage")
Multiple Options
# Check multiple valid options
color = "red"
if color == "red" or color == "blue" or color == "green":
print("Primary color")
Create a simple login system with username and password:
# Valid credentials
VALID_USERNAME = "admin"
VALID_PASSWORD = "secret123"
# Get user input
username = input("Username: ")
password = input("Password: ")
# Check credentials
if username == VALID_USERNAME and password == VALID_PASSWORD:
print("Access granted!")
else:
print("Access denied!")
Classify temperature based on multiple conditions:
temp = float(input("Enter temperature: "))
if temp < 0:
print("Freezing!")
elif temp >= 0 and temp < 20:
print("Cold")
elif temp >= 20 and temp < 30:
print("Pleasant")
else:
print("Hot!")
🎉 Summary
You've learned about:
- Using logical operators (and, or, not)
- Combining multiple conditions
- Understanding operator precedence
- Common patterns with conditions