Introduction: What Are if
, elif
, and else
Statements in Python?
If-Elif-Else: Let’s say your program needs to make a choice—something like, “If it’s raining, grab an umbrella. If it’s sunny, wear sunglasses. Otherwise, just go as you are.” In Python, we use if
, elif
, and else
to handle exactly that kind of logic.
These statements let your program make decisions based on conditions. So instead of running the same thing every time, it can react differently depending on what’s happening.
In this guide, I’ll show you what these statements are, why they’re important, and how to use them with easy-to-follow examples. No confusing codes—just clear, simple steps to help you get the hang of it.
Let’s jump in and make Python a little smarter, one condition at a time.

What Is an If-Else Statement in Python?

Let’s start with the basics. An if-else statement in Python helps your program make a choice between two options.
It works like this:
- If a certain condition is true, it runs one block of code.
- If not, it runs a different block.
Here’s a simple example to show how it works:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
What’s happening here?
- Python checks if
x > 5
. - Since
x
is 10, the condition is True, so it prints:x is greater than 5
- If
x
had been 5 or less, the program would’ve printed the other message.
So with just a few lines of code, your program is already making decisions like a pro.
Want to add more than two choices? That’s where elif
comes in—and we’ll look at that next!
What Does elif
Mean in Python?

So far, we’ve seen how if-else
lets us choose between two options. But what if you have more than two possible conditions?
That’s where elif
comes in. It stands for “else if”, and it lets you check multiple conditions—one after the other—until one of them is true.
Here’s a simple example:
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is 5 or less")
How does this work?
- Python checks the first condition:
x > 10
. That’s False, so it moves on. - Then it checks the
elif
:x > 5
. That’s True, so it prints:"x is greater than 5 but less than or equal to 10"
- Since one condition matched, Python skips the rest (including the
else
).
Using elif
helps you keep your code clean and readable, especially when you’re checking for 3 or more conditions.
Up next, we’ll combine all three—if
, elif
, and else
—in one neat example to show how they work together in real life.
Python if-elif-else
Statement Syntax
Now that you’ve seen a few examples, let’s look at the general syntax of how if-elif-else
statements work in Python.

Here’s the basic structure:
if condition1:
# Code runs if condition1 is True
elif condition2:
# Code runs if condition2 is True
else:
# Code runs if none of the above conditions are True
A few key things to remember:
- Indentation matters! Python doesn’t use curly braces
{}
—it uses indentation to know which lines belong to which block. - Each condition must evaluate to True or False.
- You can have as many
elif
blocks as you need. - But you can only have one
if
and oneelse
in each statement.
Once you get used to this pattern, writing decision-making logic in Python becomes super smooth.
Next, let’s put this syntax into action with a real-life example that reacts to different inputs!
Simple If-Else Python Examples for Practice
Here’s a real-world scenario where we check if someone is eligible to vote based on their age.
Example 1: Check Voting Eligibility
We’re going to use an if-else
statement to check if someone’s age is greater than or equal to 18, which is the typical voting age in many countries.
age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
How it works:
- If the age is 18 or older, the condition
age >= 18
will be True, so it will print:"You are eligible to vote."
- If the age is less than 18, it will print:
"You are not eligible to vote."
Practice Tip:
Try changing the age
variable to see how the output changes. You can test different ages to see the if-else
logic in action!
Now, let’s step it up a bit and create a Grade Calculator using if-elif-else
. This is a real-life example where we check a student’s marks and determine their grade.
Example 2: Grade Calculator Using Elif
Here’s how we can assign grades based on the marks:
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: D")
How it works:
- If the
marks
are 90 or higher, it prints “Grade: A”. - For marks between 75 and 89, the grade will be ‘B.’
- If the marks are between 60 and 74, it prints “Grade: C”.
- If the marks are below 60, it prints “Grade: D”.
Practice Tip:
Try changing the marks
variable to different values and observe how the output changes depending on which condition matches. This will help you understand how the program checks each condition in order.
Feel free to modify the grade ranges or add more conditions to experiment with different scenarios!
Now, let’s talk about nested if-else statements in Python. This happens when you place an if-else
block inside another if
block. It’s useful when you need to check multiple conditions within a single decision-making process.
Nested If-Else in Python Explained
In a nested if-else
, the program first checks one condition, and if it’s true, it will check another condition inside that first condition. Here’s an example:
x = 15
if x > 10:
if x < 20:
print("x is between 11 and 19")
else:
print("x is 20 or more")
else:
print("x is 10 or less")
How this works:
- First, Python checks if
x > 10
. Sincex
is 15, the condition is True, so it moves to the next step. - Inside the first
if
block, Python checks ifx < 20
. Sincex
is 15, this condition is also True, so it prints:"x is between 11 and 19"
- If
x
had been greater than or equal to 20, Python would’ve executed theelse
block and printed:"x is 20 or more"
- If
x
had been 10 or less, it would’ve skipped the first block and printed:"x is 10 or less"
Key Tip:
While nested if-else
statements can be useful, it’s important to use them carefully. Too many layers can make your code harder to read and follow. Always aim for clarity when nesting!
Let’s add another nested condition to make this example a bit more complex.
Nested If-Else with More Conditions

Let’s check if x
is within different ranges: less than 10, between 10 and 20, between 20 and 30, and 30 or more. We’ll nest the conditions to handle these cases.
Here’s the updated code:
x = 25
if x < 10:
print("x is less than 10")
elif x >= 10 and x < 20:
if x == 15:
print("x is exactly 15")
else:
print("x is between 10 and 19, but not exactly 15")
elif x >= 20 and x < 30:
print("x is between 20 and 29")
else:
print("x is 30 or more")
How this works:
- The first condition checks if
x
is less than 10. If it were, it would print:"x is less than 10"
. - If
x
is between 10 and 19, it checks if it’s exactly 15 with the nestedif
. If it’s exactly 15, it prints:"x is exactly 15"
. Otherwise, it prints:"x is between 10 and 19, but not exactly 15"
. - For values of x between 20 and 29, the program will print: ‘x is between 20 and 29.’
- If none of the above conditions are true (meaning
x
is 30 or more), it prints:"x is 30 or more"
.
Practice Tip:
You can try changing the value of x
and observe how the program reacts. This is a great way to get comfortable with nested conditions and how Python checks them.
Let’s dive into some common mistakes to avoid when using if-elif-else
statements in Python, so you can write cleaner, more effective code without running into frustrating errors.
Must Read
- How to Return Multiple Values from a Function in Python
- Parameter Passing Techniques in Python: A Complete Guide
- A Complete Guide to Python Function Arguments
- How to Create and Use Functions in Python
- Find All Divisors of a Number in Python
Common Mistakes to Avoid with If-Elif-Else
in Python

1. Missing Indentation
Python uses indentation to define the blocks of code that belong to each if
, elif
, or else
statement. If you forget to indent properly, Python will throw an IndentationError. Here’s an example of what not to do:
x = 10
if x > 5:
print("wrong") # This will throw an IndentationError
Why it happens:
In the code above, the print
statement is not indented correctly under the if
block, so Python doesn’t know that it’s part of the if
statement.
Correct version:
x = 10
if x > 5:
print("Correct") # Indentation is fixed!
2. Using elif
Without an Initial if
Another mistake is trying to use elif
without a preceding if
. The elif
block can only be used after an if
block, or another elif
block. Here’s what can go wrong:
x = 10
elif x > 5: # This will throw a SyntaxError
print("x is greater than 5")
Why it happens:
You can’t start with elif
directly—it needs an initial if
block to check the first condition.
Correct version:
x = 10
if x > 5:
print("x is greater than 5")
3. Using Assignment (=
) Instead of Comparison (==
)
This is a subtle mistake where you accidentally use the assignment operator (=
) instead of the comparison operator (==
). This can lead to unexpected behavior in your code.
x = 10
if x = 10: # This will throw a SyntaxError
print("x is 10")
Why it happens:
The assignment operator =
is used to assign a value to a variable, not to compare values. In the above case, you’re mistakenly trying to use =
in an if
condition instead of ==
for comparison.
Correct version:
x = 10
if x == 10: # Use '==' for comparison, not '=' for assignment
print("x is 10")
Key Takeaways:
- Indentation is crucial in Python. Always indent the code inside
if
,elif
, andelse
blocks properly. - Always use
if
beforeelif
. - Use
==
for comparisons, not=
.
By avoiding these mistakes, your if-elif-else
statements will work as expected and your code will be cleaner and easier to debug.
When to Use If
, Elif
, or Else
in Python

Understanding when to use if
, elif
, and else
will help you control the flow of your program and make decisions based on different conditions. Here’s a breakdown of when each one should be used:
Use if
when:
You need to check the first condition.
- The
if
statement is used to evaluate the first condition in your decision-making process. - If the condition is True, the block of code inside the
if
runs.
Example:
x = 10
if x > 5:
print("x is greater than 5") # This will run because the condition is True
In this example, if
is checking whether x > 5
. Since it’s the first condition in our decision structure, we start with if
.
Use elif
when:
You need to check additional conditions after the initial if
.
elif
stands for “else if” and is used when you have multiple conditions to check after the initialif
.- If the condition of the
if
statement is False, the program moves to the nextelif
(if there is one) and checks it. - You can use as many
elif
blocks as needed.
Example:
x = 15
if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is greater than 10 but less than or equal to 20") # This will run because x is 15
Here, the elif
is checking if x
is greater than 10 after the initial if
condition (x > 20
) is False. If x > 10
is True, the code inside the elif
block will execute.
Use else
when:
You want a default block to run if no conditions match.
- The
else
block runs when none of the above conditions are True. - You don’t need to specify any condition for the
else
—it’s simply a fallback option when allif
andelif
conditions fail.
Example:
x = 5
if x > 10:
print("x is greater than 10")
elif x > 7:
print("x is greater than 7 but less than or equal to 10")
else:
print("x is 7 or less") # This will run because both previous conditions are False
In this case, since both the if
and elif
conditions are False, the else
block executes, providing the default output.
Summary:
if
is used when you need to check the first condition.elif
is used for additional conditions after the initialif
.else
is used as a catch-all default block when no conditions are met.
By following these rules, you can structure your Python programs to handle all kinds of decision-making processes smoothly!
Real-Life Use Cases of Python Conditional Statements
Let’s break down these real-life examples step by step to understand how if-elif-else statements work in Python. I’ll guide you through each one, explaining the logic behind it and showing how you can use these statements in real-world programs.
1. Login Systems: Checking if Username and Password Match
Imagine you want to build a simple login system. You need to check whether the username and password entered by the user match the stored ones. This is a classic example of using conditional statements in Python.
Here’s how we can break it down:
- First, we’ll ask the user to enter their username and password.
- We’ll then compare the entered username and password with the stored ones.
- If both match, the login is successful. If not, the user is shown an error message.
Code Example:
# Stored credentials
stored_username = "user123"
stored_password = "pass123"
# Ask the user to input their username and password
username = input("Enter your username: ")
password = input("Enter your password: ")
# Check if both the username and password match
if username == stored_username and password == stored_password:
print("Login successful!")
else:
print("Invalid username or password.")
Explanation:
input()
: This function asks the user to type in their username and password.if username == stored_username and password == stored_password
: This line checks whether both the username and password match the stored values.- If both conditions are True, the code inside the
if
block runs, and the user is logged in. - and If either condition is False, the
else
block runs, and the user is shown an error message.
2. Games: Triggering Different Actions Based on Player Input
In a game, you might want to check the player’s input and trigger different actions based on their choice. Let’s look at a simple example where the player can either choose to fight or run.
Code Example:
# Ask the player for their action
action = input("Do you want to 'fight' or 'run'? ").lower()
# Check if the action is to fight or run
if action == 'fight':
print("You engage in battle!")
elif action == 'run':
print("You flee from the battle!")
else:
print("Invalid action. Please choose 'fight' or 'run'.")
Explanation:
input()
: This function gets the player’s input. The.lower()
method ensures that it’s case-insensitive (so “Fight” and “fight” will both be accepted).if action == 'fight'
: If the player’s action is “fight”, the first block of code runs.elif action == 'run'
: If the action isn’t “fight”, the program checks if it’s “run”. If True, it runs that block.else
: If the player enters anything other than “fight” or “run”, theelse
block runs, prompting them to enter a valid action.
3. Forms: Validating Age and Email Before Submission
You can also use conditional statements to validate data entered by users in forms. For instance, checking if the user is old enough to use a service or if the email they provided is valid.
Code Example:
# Ask the user to enter their age
age = int(input("Enter your age: "))
# Check if the age is valid for submission
if age < 18:
print("Sorry, you must be at least 18 years old to submit this form.")
else:
# If age is valid, check if the email is valid
email = input("Enter your email address: ")
if "@" in email and "." in email:
print("Form submitted successfully!")
else:
print("Please enter a valid email address.")
Explanation:
input()
: This asks the user for their age and email.if age < 18
: If the user is younger than 18, the program shows a message saying they’re not eligible.else
: If the user is 18 or older, it asks for their email.if "@" in email and "." in email
: This checks whether the email contains both “@” and “.”. It’s a simple validation to make sure the email is somewhat correct.else
: If the email is invalid, the user is prompted to enter a valid email address.
Key Takeaways:
- Login System: We used
if
andelse
to check whether the entered username and password matched the stored ones. - Game Actions: We used
if
,elif
, andelse
to handle different choices made by the player. - Form Validation: We used
if
,else
, and nested conditionals to validate the user’s age and email.
Conclusion: Mastering Python’s Conditional Statements
Now that you’ve learned how to use if-elif-else statements in Python, you can apply them in a variety of real-world scenarios, like creating login systems, building game logic, or validating user input in forms. These fundamental control flow tools are the backbone of most Python programs, helping you make decisions and manage program behavior based on different conditions.
We’ve walked through simple examples, and hopefully, you’re now more comfortable using these statements in your own projects. Remember, if checks the first condition, elif handles additional conditions, and else provides a default when no other conditions match.
Keep experimenting, and soon you’ll be creating more complex programs with ease.
Quiz Challenge
Basic If-Else Logic
1. What will be the output of the following code?
x = 20
if x > 25:
print(“x is greater than 25”)
else:
print(“x is less than or equal to 25”)
A) x is greater than 25
B) x is less than or equal to 25
C) Error
D) No output
Answer: B) x is less than or equal to 25
Explanation: The value of x
is 20, which is less than 25. Since the condition x > 25
is False, the program moves to the else
block, printing "x is less than or equal to 25"
.
Using Elif for Multiple Conditions
2. What will the following code print?
x = 7
if x > 10:
print(“x is greater than 10”)
elif x > 5:
print(“x is greater than 5 but less than or equal to 10”)
else:
print(“x is 5 or less”)
A) x is greater than 10
B) x is greater than 5 but less than or equal to 10
C) x is 5 or less
D) None of the above
Answer: B) x is greater than 5 but less than or equal to 10
Explanation: The value of x
is 7. The first if
condition (x > 10
) is False, so the program checks the elif
condition (x > 5
). Since x = 7
, which satisfies x > 5
, the program prints "x is greater than 5 but less than or equal to 10"
.
Nested If-Else
3. What will be the output of the following code?
x = 5
if x > 3:
if x < 10:
print(“x is between 4 and 9”)
else:
print(“x is 10 or more”)
else:
print(“x is 3 or less”)
A) x is between 4 and 9
B) x is 10 or more
C) x is 3 or less
D) None of the above
Answer: A) x is between 4 and 9
Explanation: The value of x
is 5. The first if
condition (x > 3
) is True, so the program proceeds to the nested if
statement. Since x = 5
satisfies x < 10
, it prints "x is between 4 and 9"
.
Comparing If-Elif-Else with Multiple Conditions
4. What is the output of the following code?
marks = 85
if marks >= 90:
print(“Grade: A”)
elif marks >= 75:
print(“Grade: B”)
elif marks >= 60:
print(“Grade: C”)
else:
print(“Grade: D”)
A) Grade: A
B) Grade: B
C) Grade: C
D) Grade: D
Answer: B) Grade: B
Explanation: The value of marks
is 85. The first if
condition (marks >= 90
) is False, so the program checks the elif
condition (marks >= 75
). Since marks = 85
, the program prints "Grade: B"
.
Conditional Blocks and Indentation
5. Which of the following code snippets will result in an IndentationError?
x = 10
if x > 5:
print(“x is greater than 5”) # Error here
A) Code runs fine
B) IndentationError
C) SyntaxError
D) None of the above
Answer: B) IndentationError
Explanation: In Python, indentation is crucial. The line print("x is greater than 5")
must be indented under the if
statement. Without indentation, Python will raise an IndentationError because it can’t determine which block the print()
statement belongs to.
External Resources
Python Official Documentation on Conditional Statements
W3Schools – Python If…Else
GeeksforGeeks – Python If Else Statements
Python Tutor – Visualize Python Code
- Link: http://pythontutor.com/
FAQs
If-elif-else statements in Python are used for decision-making. They allow you to check multiple conditions and execute code based on the first condition that evaluates to true. The if
checks the first condition, elif
handles additional conditions, and else
covers the default case if none of the conditions are met.
To check multiple conditions in Python, you can use multiple elif
statements after the initial if
. Each elif
checks for a new condition, and the else
statement provides a default action if none of the conditions are true.
Yes, you can use nested if-else statements in Python. This means you can place an if
statement inside another if
or else
block. It helps in checking more complex conditions but should be used carefully to avoid confusion.
if
and elif
in Python? The if
statement checks the first condition, while elif
(else if) checks additional conditions if the previous ones were false. You can have multiple elif
statements to check for various possibilities before using else
as the final fallback.
Leave a Reply