Python Elif Statement
In programming, we often need to make decisions based on multiple conditions. While the if-else
structure allows us to handle two possible scenarios, real-world situations frequently require more complex decision-making. This is where Python's elif
statement comes into play.
What is the Elif Statement?
The elif
statement (short for "else if") is used when you need to check multiple conditions in sequence. It allows you to create decision trees where Python evaluates each condition in order until it finds one that's True
.
The basic structure looks like this:
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False and condition2 is True
elif condition3:
# Code to execute if condition1 and condition2 are False and condition3 is True
else:
# Code to execute if all conditions are False
How Elif Works
When Python encounters an if-elif-else structure:
- It evaluates the first
if
condition. - If that condition is
True
, it executes the code block under theif
statement and skips all other conditions. - If the first condition is
False
, it moves to the firstelif
condition. - It continues this process through all
elif
conditions until it finds one that'sTrue
. - If none of the conditions are
True
, it executes theelse
block (if one exists).
Basic Elif Example
Let's look at a simple example that grades a student's score:
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'
print(f"Your grade is: {grade}")
Output:
Your grade is: B
In this example:
- Python checks if the score is 90 or above. It's not, so it moves to the first
elif
. - It checks if the score is 80 or above. It is (85), so it assigns 'B' to
grade
and skips all remaining conditions. - Finally, it prints the grade.
Multiple Elif Statements
You can have as many elif
blocks as necessary. Here's an example that recommends activities based on weather:
weather = "rainy"
if weather == "sunny":
activity = "Go for a hike"
elif weather == "cloudy":
activity = "Visit a museum"
elif weather == "rainy":
activity = "Read a book indoors"
elif weather == "snowy":
activity = "Build a snowman"
else:
activity = "Check the weather forecast again"
print(f"Recommended activity: {activity}")
Output:
Recommended activity: Read a book indoors
Combining Conditions in Elif Statements
You can use logical operators (and
, or
, not
) to create more complex conditions:
temperature = 28
weather_condition = "sunny"
if temperature > 30 and weather_condition == "sunny":
recommendation = "Stay hydrated and find shade"
elif temperature > 25 and weather_condition == "sunny":
recommendation = "Perfect for the beach"
elif temperature > 20 or weather_condition != "rainy":
recommendation = "Good for outdoor activities"
else:
recommendation = "Maybe stay indoors today"
print(recommendation)
Output:
Perfect for the beach
Nested Elif Statements
You can also nest if-elif-else structures inside each other for more complex decision trees:
day = "weekend"
weather = "sunny"
temperature = 22
if day == "weekend":
if weather == "sunny" and temperature > 25:
plan = "Go to the beach"
elif weather == "sunny":
plan = "Go for a picnic"
else:
plan = "Watch a movie at home"
elif day == "weekday":
if temperature < 0:
plan = "Work from home if possible"
else:
plan = "Go to work"
else:
plan = "Check your calendar"
print(f"Today's plan: {plan}")
Output:
Today's plan: Go for a picnic
Real-World Applications
1. Simple Calculator
Let's create a basic calculator that performs different operations based on user input:
num1 = 10
num2 = 5
operation = "multiply"
if operation == "add":
result = num1 + num2
elif operation == "subtract":
result = num1 - num2
elif operation == "multiply":
result = num1 * num2
elif operation == "divide":
if num2 != 0: # Avoid division by zero
result = num1 / num2
else:
result = "Error: Division by zero"
else:
result = "Invalid operation"
print(f"Result of {operation}: {result}")
Output:
Result of multiply: 50
2. Time-Based Greeting
A program that greets users differently based on the time of day:
import datetime
current_hour = datetime.datetime.now().hour
if current_hour < 12:
greeting = "Good morning!"
elif current_hour < 17:
greeting = "Good afternoon!"
elif current_hour < 21:
greeting = "Good evening!"
else:
greeting = "Good night!"
print(greeting)
Output: (will vary based on the time you run it)
Good afternoon!
3. Discount Calculator
A program that calculates discounts based on purchase amount:
purchase_amount = 120
if purchase_amount >= 300:
discount = 0.25 # 25% discount
elif purchase_amount >= 200:
discount = 0.15 # 15% discount
elif purchase_amount >= 100:
discount = 0.10 # 10% discount
else:
discount = 0 # No discount
discount_amount = purchase_amount * discount
final_price = purchase_amount - discount_amount
print(f"Purchase amount: ${purchase_amount}")
print(f"Discount: ${discount_amount:.2f} ({discount*100:.0f}%)")
print(f"Final price: ${final_price:.2f}")
Output:
Purchase amount: $120
Discount: $12.00 (10%)
Final price: $108.00
Best Practices for Using Elif
- Order your conditions carefully: Place more specific or common conditions first for efficiency.
- Keep readability in mind: If you have many
elif
statements, consider using a dictionary or match-case statement (Python 3.10+) instead. - Avoid deep nesting: Too many nested if-elif structures can make your code hard to read.
- Use meaningful variable names: This helps clarify the purpose of your conditionals.
Summary
The elif
statement is a powerful tool in Python that allows you to create multi-way decision structures. By chaining multiple conditions together, you can handle complex decision-making scenarios in your programs.
To use elif
effectively:
- Start with an
if
statement for your first condition - Add as many
elif
statements as needed for additional conditions - Optionally end with an
else
statement as a catch-all - Remember that Python stops checking conditions once it finds a
True
one
Practice Exercises
- Create a BMI calculator that categorizes results as underweight, normal, overweight, or obese.
- Write a program that converts a numeric month (1-12) to its name (January-December).
- Create a movie ticket pricer that gives different prices based on age (child, adult, senior) and day of the week.
- Make a simple adventure game where users choose paths with different outcomes using if-elif structures.
Additional Resources
- Python Documentation on Control Flow
- Real Python: Conditional Statements in Python
- W3Schools Python Conditions
Now that you understand the elif
statement, you have a powerful tool for handling multiple conditions in your Python programs. This is a fundamental concept you'll use in almost every program you write!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)