How to use 'elif' in Python

Learn to use Python's elif statement with examples and tips. See real-world applications and learn how to debug common errors.

How to use 'elif' in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Tue
Feb 24, 2026
The Replit Team Logo Image
The Replit Team

The elif statement in Python lets you check multiple conditions in sequence. It is a key tool to create clean, readable logic when a simple if-else structure falls short.

You'll discover techniques to master elif for complex conditional flows. You will see real-world applications and get practical advice to debug common errors, which helps you write more efficient Python 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 code first evaluates the if condition: age < 18. Because the variable age is 25, this condition is false, and the program skips to the next part of the statement.

This is where elif comes in. It checks the next condition, age >= 18, only after the initial if fails. Since this is true, its code block runs, and the entire conditional check ends. This structure ensures that only one of the conditions in the chain is ever executed.

Common patterns with elif

Beyond a single check, the elif statement's real strength shines when you chain multiple conditions, use logical operators, or define specific value ranges.

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

This pattern is ideal for assigning a value based on a range, like in this grading example. Python evaluates each condition sequentially from top to bottom.

  • The initial if condition (score >= 90) is false.
  • The program moves to the first elif, where score >= 80 is true. Its code runs, and the entire block terminates.

The order of your elif statements is crucial. If the check for score >= 70 came before score >= 80, a score of 85 would incorrectly result in "Grade: C".

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 create more precise checks by combining elif with logical operators. The condition 20 <= temp < 30 is a Python shorthand for checking if a value falls within a specific range—it's a cleaner way to write temp >= 20 and temp < 30.

  • With temp set to 28, the first two conditions for "Freezing" and "Cold" are false.
  • The program then evaluates 20 <= temp < 30, which is true. It prints "Warm," and the entire conditional block terminates.

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 pattern neatly categorizes an age into specific life stages using non-overlapping ranges. Python's chained comparison syntax, like 20 <= age < 60, is a readable way to check if a value falls between two points.

  • Since age is 35, the conditions for "Child" and "Teenager" are false.
  • The program proceeds to the next elif, where 20 <= age < 60 evaluates to true.
  • It prints "Adult," and the conditional block terminates immediately.

Advanced techniques with elif

With these common patterns mastered, you can now handle more complex logic by nesting elif statements, calling functions, or optimizing long chains with dictionaries.

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

You can nest conditional statements to handle more complex logic. The outer if-elif block first evaluates the weather. Because weather is "rainy", the program executes the code within the elif block and ignores the initial if statement entirely.

  • Inside the elif block, a second, nested conditional checks the temp.
  • Since temp is 15, the condition temp < 10 is false, so the inner else block runs.

This layered approach is great for creating decision trees where one choice narrows down the next set of options.

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

You can embed elif logic inside functions to create clean, reusable code. The get_day_type function uses the .lower() method to handle case-insensitive inputs like "Sunday" or "sunday" equally.

  • The initial if checks if the day is a weekend day using the in operator.
  • If not, the elif condition checks if it's a weekday.

Using return within each block sends the result back, making the function a self-contained tool you can call anywhere in your program.

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 conditional chains that map one value to another, a dictionary is often a cleaner and more efficient solution. This pattern avoids a lengthy series of elif statements by directly looking up a key.

  • The .get() method retrieves a value for a key, like day_number or status_code.
  • It also accepts a default value—such as "Weekend" or "Unknown Status"—which is returned if the key isn't found. This neatly replaces the need for a final else block.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

The conditional logic patterns you've just learned can be turned into production-ready tools. With Replit Agent, you can build applications that use elif structures to handle complex decisions:

  • A grading calculator that automatically assigns letter grades based on scores.
  • A diagnostic tool that interprets status codes and suggests next steps, replacing long elif chains.
  • A smart notification system that sends different alerts based on weather and temperature, using nested conditional logic.

Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically. Start building your next project with Replit Agent.

Common errors and challenges

While elif simplifies complex logic, a few common pitfalls can lead to bugs, from incorrect condition order to mishandling logical operators.

  • Incorrect condition order leading to unreachable code with elif: The sequence of your elif statements is critical because Python stops at the first true condition. Placing a general condition before a more specific one makes the specific check unreachable, leading to subtle bugs that are hard to find.
  • Forgetting to handle unexpected inputs with else: An if-elif chain without a final else block can fail silently if no conditions are met. This block acts as a safety net, catching unexpected values and ensuring your program always behaves predictably instead of doing nothing.
  • Confusing and and or operators in elif conditions: Using the wrong logical operator alters your logic entirely. The and operator requires all conditions to be true, ideal for ranges, while or only needs one. Accidentally using or can make a condition too broad, causing code to run when it shouldn't.

Incorrect condition order leading to unreachable code with elif

The order of your elif conditions is critical. Placing a general check before a more specific one can make the latter unreachable, as Python stops evaluating at the first true statement it finds. This creates a subtle but significant logic error.

In the following code, a score of 85 should result in a grade of "B". Notice how the incorrect order of the conditions leads to the wrong output.

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}")

The code stops at the first true condition, score >= 70, so the more specific check for score >= 80 never runs. This results in the wrong grade. The corrected version below fixes 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. It first checks for a score of 90 or higher. Since 85 fails this, it moves to the elif score >= 80 condition, which is true, and the program stops. This ensures the correct grade is assigned.

This error often appears in grading systems or any logic involving numerical ranges. Always place your strictest condition first to ensure every case is evaluated correctly.

Forgetting to handle unexpected inputs with else

An if-elif chain without a final else block can cause silent failures when an input doesn't match any condition. This oversight means your program might return nothing or behave unpredictably. The following code demonstrates what happens when the get_weekday function receives an unexpected value.

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

Since the input 9 doesn't match any condition in the get_weekday() function, it completes without an explicit return. Python then defaults to returning None, causing the unexpected output. The following example shows how to make the function more robust.

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 as a safety net. It returns a clear message when the input doesn't match any if or elif condition, preventing the function from silently returning None. This is crucial for functions that process user input or external data, where unexpected values are common. Using an else block makes your code more robust and easier to debug by explicitly handling all other cases.

Confusing and and or operators in elif conditions

It's easy to mix up the and and or operators, but doing so can break your logic. Remember, and needs every condition to be true, while or just needs one. Using the wrong one can create a check that's impossible to pass. See what happens in the code below when and is used incorrectly.

payment_method = "credit"
if payment_method == "credit" and payment_method == "debit":  # Cannot be both at once
   print("Card payment")
else:
   print("Other payment")

The if condition is impossible to satisfy. The and operator requires the payment_method variable to be both "credit" and "debit" simultaneously, which can never happen. The corrected code shows the right way to structure this check.

payment_method = "credit"
if payment_method == "credit" or payment_method == "debit":
   print("Card payment")
else:
   print("Other payment")

The corrected code works because the or operator only needs one condition to be true. It correctly checks if payment_method is either "credit" or "debit", allowing the code to run as intended. You'll often encounter this situation when checking if a variable matches any value from a specific set. It's a good habit to pause and confirm your logical operators—and versus or—to avoid these simple but frustrating bugs.

Real-world applications

Now that you know how to sidestep common pitfalls, you can see how elif powers applications like automated message sorting and weather advisories.

Using elif for customer support message categorization

An if-elif-else chain can scan incoming messages for keywords to automatically sort them into the correct categories.

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 logic processes a string by searching for specific keywords. It uses the .lower() method to make the check case-insensitive, so it doesn't matter if the original message contains "Order" or "order".

  • The code uses an if-elif chain with the in operator to find keywords.
  • The or operator allows it to check for multiple terms, like "order" or "delivery", in a single condition.

Since the message contains "order", the second condition is met, and the program assigns the corresponding string to the category variable before printing it.

Building a weather advisory system with elif

This same logic allows you to build a system that provides specific weather advice by evaluating multiple conditions, like temperature and current weather.

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"))

The get_weather_advice function shows how to handle complex decisions by checking multiple variables at once. It uses an if-elif-else structure to provide specific advice based on both temperature and weather conditions.

  • Each condition, like temp > 30 and condition == "sunny", uses the and operator, requiring both checks to be true.
  • The code evaluates these statements sequentially, executing only the first one that matches.
  • A final else block provides a default response for any combination that doesn't fit the specific criteria, ensuring the function always returns a useful message.

Get started with Replit

Turn your knowledge of elif into a real tool. Tell Replit Agent to “build a shipping cost calculator based on weight ranges” or “create a weather advisory tool that suggests activities based on temperature.”

Replit Agent writes the code, tests for errors, and deploys your app, handling the heavy lifting. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.