Understand how Python's if-elif-else statements work with this easy visual guide.
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.
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:
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")
x > 5.x is 10, the condition is True, so it prints:x is greater than 5x 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!
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")
x > 10. That’s False, so it moves on.elif: x > 5. That’s True, so it prints:"x is greater than 5 but less than or equal to 10"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.
if-elif-else Statement SyntaxNow 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
{}—it uses indentation to know which lines belong to which block.elif blocks as you need.if and one else 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!
Here’s a real-world scenario where we check if someone is eligible to vote based on their age.
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.")
age >= 18 will be True, so it will print:"You are eligible to vote.""You are not eligible to vote."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.
ElifHere’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")
marks are 90 or higher, it prints “Grade: A”.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.
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")
x > 10. Since x is 15, the condition is True, so it moves to the next step.if block, Python checks if x < 20. Since x is 15, this condition is also True, so it prints:"x is between 11 and 19"x had been greater than or equal to 20, Python would’ve executed the else block and printed:"x is 20 or more"x had been 10 or less, it would’ve skipped the first block and printed:"x is 10 or less"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.
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")
x is less than 10. If it were, it would print: "x is less than 10".x is between 10 and 19, it checks if it’s exactly 15 with the nested if. If it’s exactly 15, it prints: "x is exactly 15". Otherwise, it prints:"x is between 10 and 19, but not exactly 15".x is 30 or more), it prints: "x is 30 or more".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.
If-Elif-Else in PythonPython 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
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.
x = 10
if x > 5:
print("Correct") # Indentation is fixed!
elif Without an Initial ifAnother 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")
You can’t start with elif directly—it needs an initial if block to check the first condition.
x = 10
if x > 5:
print("x is greater than 5")
=) 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")
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.
x = 10
if x == 10: # Use '==' for comparison, not '=' for assignment
print("x is 10")
if, elif, and else blocks properly.if before elif.== 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.
If, Elif, or Else in PythonUnderstanding 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:
if when:You need to check the first condition.
if statement is used to evaluate the first condition in your decision-making process.if runs.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.
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 initial if.if statement is False, the program moves to the next elif (if there is one) and checks it.elif blocks as needed.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.
else when:You want a default block to run if no conditions match.
else block runs when none of the above conditions are True.else—it’s simply a fallback option when all if and elif conditions fail.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.
if is used when you need to check the first condition.elif is used for additional conditions after the initial if.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!
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.
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:
# 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.")
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 block runs, and the user is logged in.else block runs, and the user is shown an error message.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.
# 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'.")
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”, the else block runs, prompting them to enter a valid action.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.
# 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.")
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.if and else to check whether the entered username and password matched the stored ones.if, elif, and else to handle different choices made by the player.if, else, and nested conditionals to validate the user’s age and email.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.
x is greater than 25x is less than or equal to 25Answer: 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".
x is greater than 10x is greater than 5 but less than or equal to 10x is 5 or lessAnswer: 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".
x is between 4 and 9x is 10 or morex is 3 or lessAnswer: 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".
Grade: AGrade: BGrade: CGrade: DAnswer: 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".
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.
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.
After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.