Introduction to Conditional Logic
Imagine you're a traffic controller at a busy intersection. Just as you make decisions based on different conditions (Is the light red? Are there pedestrians waiting?), Python programs need to make decisions based on different circumstances. This is where if statements come in – they're like the decision-making brain of your program.
Think of an if statement as a friendly bouncer at a club who follows a simple set of rules: "If the person is over 21, let them in. If they're not over 21 but have a special pass, let them in. Otherwise, politely turn them away." In Python, we can express these kinds of decision trees clearly and efficiently.
Basic If Statements: Your First Decision
Let's start with the simplest form of decision-making in Python. A basic if statement is like asking a single yes/no question and acting based on the answer:
# The simple structure of an if statement
temperature = 75
# Notice: no parentheses needed (unlike JavaScript)!
if temperature > 70:
print("It's a warm day!")
print("Remember to stay hydrated!")
# Multiple conditions in one line
age = 25
has_id = True
if age >= 21 and has_id:
print("Welcome to the club!")
# Real-world example: Temperature monitoring
def check_temperature(temp):
if temp > 98.6:
print("You might have a fever")
return "Please consult a doctor"
# The code here will run if the condition is False
print("Temperature is normal")
return "You're good to go!"
# Python's clean syntax means no curly braces
# Instead, we use indentation to show what's inside the if block
The indentation in Python isn't just for making code look pretty – it's a fundamental part of the language's syntax. Think of it like creating a clear outline for your decision-making process, where each indented block shows what should happen under specific conditions.
Adding Else: The Alternative Path
Sometimes we need to specify what should happen when our condition isn't met. This is where else comes in – it's like having a backup plan:
# Basic if-else structure
time = 14 # 24-hour format
if time < 12:
print("Good morning!")
else:
print("Good afternoon!")
# Real-world example: Simple login system
def check_credentials(username, password):
if username == "admin" and password == "secure123":
return "Login successful"
else:
return "Invalid credentials"
# Another practical example: Ticket pricing
def calculate_ticket_price(age):
if age < 12:
return "Child ticket: $10"
else:
return "Adult ticket: $20"
# Notice how the else clause doesn't need a condition
# It's like saying "in all other cases, do this"
Enter elif: Handling Multiple Conditions
Real-world decisions often involve multiple conditions. This is where elif (else if) comes in. Think of it like a series of filters, each checking a different condition:
# Multiple conditions using elif
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
# Real-world example: Weather advice system
def get_weather_advice(temperature, is_raining):
if temperature > 90:
return "Stay indoors or find shade"
elif temperature > 70 and not is_raining:
return "Perfect weather for outdoor activities!"
elif temperature > 50:
return "Consider bringing a light jacket"
elif is_raining:
return "Don't forget your umbrella!"
else:
return "Dress warmly!"
# The order of conditions matters!
# More specific conditions should come first
Understanding the Importance of Order
The order of elif statements is crucial. Think of it like a water filter system, where each filter catches different things. If you put the filters in the wrong order, you might not get the results you want:
# Bad order example
def classify_age_bad(age):
if age > 0: # This will catch everything positive!
return "Alive"
elif age > 100: # This will never run
return "Centenarian"
else:
return "Invalid age"
# Good order example
def classify_age_good(age):
if age > 100: # Check most specific first
return "Centenarian"
elif age > 0: # Then more general cases
return "Alive"
else:
return "Invalid age"
# Real-world example: Discount system
def calculate_discount(purchase_amount, is_member, is_holiday):
if is_holiday and purchase_amount > 100:
return "20% holiday discount"
elif is_member and purchase_amount > 50:
return "15% member discount"
elif purchase_amount > 75:
return "10% regular discount"
else:
return "No discount available"
Advanced Patterns and Best Practices
Let's explore some more sophisticated ways to use conditional statements in Python:
# Using conditional expressions (ternary operator)
age = 20
status = "adult" if age >= 18 else "minor"
# Combining conditions with logical operators
def check_eligibility(age, income, credit_score):
if (age >= 18 and income > 30000) or credit_score > 700:
return "Eligible for loan"
return "Not eligible"
# Using 'in' with if statements
def check_permission(user_role):
if user_role in ["admin", "moderator", "supervisor"]:
return "Access granted"
return "Access denied"
# Handling complex conditions clearly
def process_order(order):
# Breaking down complex conditions for readability
is_valid_amount = order.amount > 0
has_stock = order.check_inventory()
payment_verified = order.verify_payment()
if is_valid_amount and has_stock and payment_verified:
return order.process()
elif not is_valid_amount:
return "Invalid order amount"
elif not has_stock:
return "Out of stock"
else:
return "Payment verification failed"
Common Pitfalls and How to Avoid Them
Let's look at some common mistakes and learn how to write better conditional statements:
# Mistake 1: Forgetting about edge cases
def divide_numbers_bad(a, b):
if b != 0:
return a / b
# What if b is 0? We need an else!
# Better version
def divide_numbers_good(a, b):
if b != 0:
return a / b
else:
return "Cannot divide by zero"
# Mistake 2: Too many nested if statements
def check_user_bad(user):
if user.is_active:
if user.is_verified:
if user.has_permission:
return "Access granted"
return "Access denied"
# Better version using compound conditions
def check_user_good(user):
if user.is_active and user.is_verified and user.has_permission:
return "Access granted"
return "Access denied"
# Mistake 3: Redundant else clauses
def get_status_bad(score):
if score >= 60:
return "Pass"
else:
return "Fail"
# Better version
def get_status_good(score):
if score >= 60:
return "Pass"
return "Fail" # No else needed when using return
Practice Exercises
Let's reinforce our understanding with some practical exercises:
Create a function that determines shipping cost based on multiple factors:
def calculate_shipping(distance, weight, express=False):
"""
Calculate shipping cost based on:
- Distance (in miles)
- Weight (in pounds)
- Express delivery (boolean)
Return the total shipping cost
"""
# Your code here
pass
Implement a movie ticket pricing system:
def get_ticket_price(age, day, is_3d):
"""
Calculate movie ticket price based on:
- Age (child, adult, senior)
- Day of the week (weekend premium)
- 3D or regular showing
Return the ticket price
"""
# Your code here
pass