Control flow is the backbone of any programming language, and in Python, the if-elif-else statement is your go-to tool for making decisions in code. Whether you're building a simple calculator or a complex machine learning pipeline, you'll find yourself using these conditional statements all the time.
In this post, we’ll break down how if, elif, and else work in Python, with clear examples and best practices.
Conditional statements allow your program to make decisions based on certain conditions. Think of them as the logic gates of your code: "If this is true, do that. Otherwise, do something else."
if condition1:
# Code block executed if condition1 is True
elif condition2:
# Code block executed if condition1 is False and condition2 is True
else:
# Code block executed if none of the above conditions are True
You can have:
Just an if
An if with one or more elifs
An if with an else
Or all three together
age = 20
if age < 18:
print("You are a minor.")
elif age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
You are an adult.
Python checks each condition from top to bottom:
As soon as it finds a True condition, it executes that block and skips the rest.
If none of the conditions are True, it runs the else block (if present).
Python uses indentation (usually 4 spaces) to define blocks of code. Forgetting to indent properly will raise an IndentationError.
if True:
print("This will cause an error!") # Wrong indentation
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Grade: B
Keep conditions simple and readable.
Use parentheses for clarity in complex conditions.
Avoid deeply nested if statements—consider using functions or dictionaries for cleaner logic.
You can combine conditions using and, or, and not.
temperature = 25
humidity = 60
if temperature > 20 and humidity < 70:
print("Nice weather!")
The if-elif-else structure is one of the most fundamental tools in your Python toolkit. Mastering it will help you write smarter, more responsive programs.
Next up in the series: Loops in Python – for and while explained!