How to use 'elif' in Python
Master Python's elif statement. Explore methods, real-world uses, and debugging tips for common errors to improve your code.

The elif statement in Python is a powerful tool for conditional logic. It allows you to check multiple expressions for True and execute a block of code as soon as one condition is met.
Here, you'll learn essential techniques and tips for its use. We'll cover real-world applications and common debugging advice to help you write cleaner, more efficient conditional statements in your code.
Basic usage of elif statement
age = 25
if age < 18:
print("You are a minor.")
elif age >= 18:
print("You are an adult.")--OUTPUT--You are an adult.
The elif statement here acts as a secondary check. Python first evaluates the initial if age < 18 condition. Since the variable age is 25, this expression is false, so the program skips the first block and moves on to the elif line.
At this point, the condition age >= 18 is tested. It evaluates to True, so its code block runs, and the entire conditional statement is exited. This structure is more efficient than using two separate if statements because it guarantees only one block of code executes, making it perfect for mutually exclusive scenarios.
Common patterns with elif
The elif statement becomes even more powerful when you chain multiple conditions, use logical operators, or check for specific ranges of values.
Using multiple elif statements in a sequence
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")--OUTPUT--Grade: B
In this grading example, Python evaluates each condition in order. With a score of 85, the initial if score >= 90 check fails, so the program moves to the first elif statement.
- The condition
score >= 80is true, so its code block runs, and the program prints "Grade: B". - Crucially, once a condition is met, Python exits the entire conditional chain, skipping any remaining
eliforelsestatements.
Combining elif with logical operators
temp = 28
if temp < 0:
print("Freezing")
elif temp < 10:
print("Cold")
elif 20 <= temp < 30:
print("Warm")
elif temp >= 30:
print("Hot")--OUTPUT--Warm
You can make your conditions more specific by combining elif with logical operators. In this example, the code checks temperature ranges to determine the weather description.
- The line
elif 20 <= temp < 30:is a concise way to check iftempfalls between two values. - Since
tempis 28, this condition is true, so the program prints "Warm" and exits the conditional block. This chained comparison is a clean alternative to writingelif temp >= 20 and temp < 30:.
Using elif with value ranges
age = 35
if 0 <= age < 13:
print("Child")
elif 13 <= age < 20:
print("Teenager")
elif 20 <= age < 60:
print("Adult")
elif age >= 60:
print("Senior")--OUTPUT--Adult
This example categorizes an age by checking it against a series of non-overlapping ranges. Python's chained comparison syntax, like 20 <= age < 60, makes defining these boundaries clean and readable.
- With
ageset to 35, the program evaluates the conditions sequentially until20 <= age < 60returnsTrue. It then prints "Adult" and exits the block, ignoring the finalelifstatement.
Advanced techniques with elif
Now that you've mastered the common patterns, you can elevate your conditional logic by nesting elif statements, combining them with functions, and even replacing them entirely.
Nested elif structures
weather = "rainy"
temp = 15
if weather == "sunny":
if temp > 25:
print("Hot sunny day")
else:
print("Pleasant sunny day")
elif weather == "rainy":
if temp < 10:
print("Cold rainy day")
else:
print("Mild rainy day")--OUTPUT--Mild rainy day
Nesting allows you to handle more complex scenarios by placing one conditional statement inside another. In this example, the program first evaluates the outer condition for weather. Since weather is "rainy", it enters the elif block to evaluate a second, nested condition.
- Inside this block, the program checks the
temp. - Because
tempis 15, the innerif temp < 10condition fails, so its correspondingelseblock runs, printing "Mild rainy day".
Using elif with functions and methods
def get_day_type(day):
if day.lower() in ["saturday", "sunday"]:
return "Weekend"
elif day.lower() in ["monday", "tuesday", "wednesday", "thursday", "friday"]:
return "Weekday"
else:
return "Invalid day"
print(get_day_type("Sunday"))
print(get_day_type("Monday"))--OUTPUT--Weekend
Weekday
Using elif inside a function helps organize your logic cleanly. The get_day_type function takes a day and returns its type by evaluating a series of conditions.
- It first calls the
.lower()method on the input, which makes the check case-insensitive. This is whyget_day_type("Sunday")works correctly. - The
elifstatement provides a secondary check for weekdays. If the day isn't a weekend, the program evaluates theelifcondition. If that also fails, theelseblock catches any invalid inputs.
Optimizing elif chains with dictionaries
day_number = 3
days = {1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday"}
print(days.get(day_number, "Weekend"))
status_code = 404
responses = {200: "OK", 404: "Not Found", 500: "Server Error"}
print(responses.get(status_code, "Unknown Status"))--OUTPUT--Wednesday
Not Found
For long elif chains, a dictionary often offers a cleaner and more direct solution. It's especially effective when you're mapping keys to specific values, like matching a status_code to a response message.
- The dictionary's
.get()method is central to this pattern. It attempts to find a value using a key, likeday_number. - If the key doesn't exist,
.get()returns a default value you provide—such as"Weekend"or"Unknown Status". This elegantly replaces a finalelseblock.
This approach not only improves readability but can also be more efficient than a lengthy series of conditional checks, especially when building applications with vibe coding.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques, like using elif, to building complete applications with Agent 4.
Instead of piecing together logic, describe the app you want to build. Agent 4 takes your idea and turns it into a working product. For example, you could build:
- A grade calculator that processes a list of scores and outputs the corresponding letter grade for each student.
- A simple content scheduler that categorizes posts as 'Weekday' or 'Weekend' based on the date.
- A weather-based activity recommender that suggests indoor or outdoor plans based on temperature and conditions like 'rainy' or 'sunny'.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with its straightforward syntax, a few common pitfalls can trip you up when using elif statements in your code.
Keep an eye out for these frequent challenges:
- Incorrect condition order: Since Python evaluates conditions in sequence, placing a general check before a specific one can render your
elifblock unreachable. - Forgetting an
elseblock: Anelsestatement acts as a safety net. Forgetting it can leave your code unprepared for unexpected inputs or edge cases. - Confusing logical operators: Mixing up
andandorcan make your conditions too strict or too lenient, leading to logic that doesn't work as intended.
Incorrect condition order leading to unreachable code with elif
One of the most common mistakes is ordering your conditions incorrectly. When a general condition like score >= 70 comes before a specific one like score >= 90, the more specific elif block becomes unreachable. See what happens in the code below.
score = 85
if score >= 70:
grade = "C"
elif score >= 80: # This will never execute because the first condition catches it
grade = "B"
elif score >= 90: # This will never execute for the same reason
grade = "A"
print(f"Your grade is {grade}")
Since 85 is greater than 70, the first if condition is met. The program assigns the grade "C" and exits the block, ignoring the more accurate elif checks. The following code corrects this logical error.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"Your grade is {grade}")
The corrected code works by ordering conditions from most specific to most general. By checking for score >= 90 first, you ensure that higher scores are correctly categorized before the program moves to broader checks like score >= 80. This prevents the logic from exiting prematurely with the wrong grade. Always arrange your if/elif chain from the narrowest to the widest condition, especially when working with numerical ranges, to avoid this common logical error.
Forgetting to handle unexpected inputs with else
Forgetting an else block leaves your code vulnerable to unexpected inputs. When a value doesn't match any if or elif conditions, the function may return None by default, leading to silent failures. The following get_weekday function shows this in action.
def get_weekday(day_num):
if day_num == 1:
return "Monday"
elif day_num == 2:
return "Tuesday"
elif day_num == 3:
return "Wednesday"
print(get_weekday(9)) # Returns None
The input 9 doesn't match any if or elif condition. Without a fallback, the get_weekday function implicitly returns None, which can cause silent errors. See how the corrected code below handles these unexpected cases gracefully.
def get_weekday(day_num):
if day_num == 1:
return "Monday"
elif day_num == 2:
return "Tuesday"
elif day_num == 3:
return "Wednesday"
else:
return "Invalid day number"
print(get_weekday(9)) # Returns "Invalid day number"
The corrected get_weekday function adds an else block to act as a safety net. It catches any day_num that doesn't match the preceding if or elif conditions. Instead of implicitly returning None, the function now provides a clear, descriptive message.
This makes your code more robust by explicitly handling invalid inputs. Always consider adding an else block when your conditional logic must account for every possible case, preventing silent errors.
Confusing and and or operators in elif conditions
Mixing up the and and or operators can create impossible conditions that always fail. This common mistake makes your logic faulty, as a variable can't hold two different values at once. See how this plays out in the following code.
payment_method = "credit"
if payment_method == "credit" and payment_method == "debit": # Cannot be both at once
print("Card payment")
else:
print("Other payment")
The and operator creates an impossible condition, as payment_method can't be two values at once. This guarantees the else block always executes, leading to incorrect output. The corrected code below resolves this logical flaw.
payment_method = "credit"
if payment_method == "credit" or payment_method == "debit":
print("Card payment")
else:
print("Other payment")
The corrected code uses the or operator, which makes the condition true if payment_method is either "credit" or "debit". This correctly handles cases where you need to check for one of several possible values. The original and operator failed because a variable can't hold two different values simultaneously. You'll want to watch for this when checking a variable against a list of acceptable, but distinct, options.
Real-world applications
Beyond debugging, elif statements are fundamental to building practical applications, from categorizing support messages to issuing weather advisories.
Using elif for customer support message categorization
This pattern is ideal for building a simple support ticket system, where an if/elif chain scans messages for keywords to assign the correct category.
message = "My order #12345 hasn't arrived yet"
if "password" in message.lower() or "login" in message.lower():
category = "Account Issues"
elif "order" in message.lower() or "delivery" in message.lower():
category = "Order Tracking"
elif "refund" in message.lower() or "return" in message.lower():
category = "Returns & Refunds"
else:
category = "General Inquiry"
print(f"Support ticket category: {category}")
This code automatically categorizes a text message by scanning it for specific keywords. It uses the .lower() method to make the search case-insensitive, so it doesn't matter if a user types "Order" or "order".
- The
if/elifchain checks for keywords using theinoperator combined withorto group related terms like"order"and"delivery". - Once a condition is met, a category is assigned, and the logic exits the block.
- The final
elsestatement serves as a catch-all, assigning a default category if no keywords are found.
Building a weather advisory system with elif
This pattern is also perfect for building a simple advisory system where an if/elif chain checks multiple conditions, like temperature and weather, to provide tailored recommendations.
def get_weather_advice(temp, condition):
if temp > 30 and condition == "sunny":
return "Stay hydrated and use sunscreen"
elif temp > 30 and condition == "cloudy":
return "It's hot but clouds provide some relief"
elif 15 <= temp <= 30 and condition == "rainy":
return "Take an umbrella with you"
elif temp < 5:
return "Dress warmly, it's very cold"
else:
return "Weather is moderate, enjoy your day"
print(get_weather_advice(32, "sunny"))
This get_weather_advice function shows how you can create nuanced logic by combining multiple variables in your conditional checks. It’s a practical way to build a decision-making flow with elif.
- The
ifandelifstatements use theandoperator to evaluate bothtempandconditionat the same time, which allows for highly specific recommendations. - Notice the use of chained comparisons like
15 <= temp <= 30to cleanly check if a value falls within a range.
The final else block serves as a catch-all, ensuring the function always returns a helpful message.
Get started with Replit
Now, turn your understanding of elif into a real tool. Describe what you want to build to Replit Agent, like “a script that categorizes support tickets by keyword” or “a calculator that applies tiered discounts.”
Replit Agent writes the code, tests for errors, and deploys the app directly from your browser. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



