Clearing the Confusion: Understanding the Differences and Usage of Nested "If", Multiple "if" and "elif" statements in Python

I was confused about this for a while and If you're facing the same issue too, this article should give you some clarity. Fingers crossed!

A few days ago, I kicked off my Python journey with the 100 days of code challenge where I'd commit to building a project or learning python for at least one hour every day for 100 days. (Well, looks like it's going to take longer than that).

On day 3, I came across the "If/elif" statements and I found it quite easy to comprehend as I was able to solve various challenges around it. Then came the "elif" and the multiple "If" and nested "If" statements and then I was gradually losing my mind for about an hour. Two hours even. Okay, maybe for a whole day!

Many beginner Python developers may experience this same confusion when using multiple "if" and "elif" statements in their code. It can be difficult to understand the differences between these statements and when to use each one.

This article aims to clear up these confusions and provide a better understanding of the differences and usage of these statements in Python.

Trust me, if you're confused about this, it's easier than you think. Or not.

Understanding the Basics of "if" and "elif" in Python

What is an "if" statement?

An "if" statement in Python is a way for the computer to make a decision.

It checks if a certain condition is TRUE or FALSE.

If the condition is TRUE, the computer will do something, like run a certain piece of code.

If the condition is FALSE, the computer will do something else, like skip that piece of code or execute a different piece of code.

For example:

raining = Input("Is it raining outside? Yes or No ")

if raining == "Yes":
    print("Take an umbrella with you on your way out!")
else:
    print("There's no need for you to take an umbrella with you outside.")

If your answer is "Yes", the output will be: Take an umbrella with you on your way out!

If your answer is "No", the output will be: There's no need for you to take an umbrella with you outside.

If something is TRUE, the computer will do one thing. If it's NOT TRUE, the computer will do another.

Following? Okay, let's move on.

Now that you understand what the "if" statement means, let's move to the "elif" statement.

What is an elif statement?

An "elif" statement is a short word for "else if" in Python.

We use this "elif" statement when we want to check for more than one condition in our code.

For example:

If we want to check if a person is older than 18 and if they are taller than 6 feet, we can use "if" and "elif" statements to check for both conditions.

"elif" is used after an "if" statement.

Note: This is mandatory, meaning an elif always comes after an "if" and not otherwise.

I mean, you use the "elif" before the "if" statement, what next? Why don't you just wear shoes before trousers or teach your kids to walk before they crawl?

Those scenarios are kinda impossible, right? (Well, the first is something I could do).

With this "elif", your computer program checks:

If the first condition is TRUE. If it's not, then it checks the next condition.

If the second condition is TRUE, it will then execute the code. Note: this is the "elif" statement.

If the second condition is not TRUE, then it will move on to the next "elif" statement or the "else" statement.

It's like asking:

"If this condition A is not TRUE, then is this condition B TRUE?"

Or it's like:

"Let's find the right match between letters, "X" does not match "N", this is FALSE. Next, please!

...oh, yeah, "X" matches with this "X" . So, this is TRUE."

A sample code snippet:

age = int(input("What is your age? "))

if age < 18:
    print("You are too young to ride the rollercoaster!")
elif age >= 70:
    print("You are too old to ride the rollercoaster!")
else:
    print("You can ride the rollercoaster!")

If the person is 10 years old, the output will be: "You are too young to ride the rollercoaster!"

If the person is 19 years old, the output will be "You can ride the rollercoaster!"

If the person is 72 years old, the output will be "You are too old to ride the rollercoaster!"

Easy peasy, right?

The Differences Between "if" and "elif" in Python

By now, it should pretty much be clear what the differences between these two statements are. But if that's not the case, I got you.

Here is what you need to know:

"if" and "elif" are like helpers in our code.

"if" checks if a condition is TRUE or FALSE, and if it's TRUE, it executes a piece of code.

"elif" is like a helper to "if", it checks if the first helper didn't find what it was looking for and it checks another condition on its behalf.

As I said, it's almost like asking "if this condition A is not TRUE, then is this TRUE?".

For example, let's say we want to check if a person is old enough and tall enough to play basketball.

Here's a sample code snippet:

age = int(input("What is your age? "))
height = int(input("What is your height? "))

if age > 18:
    print("You are old enough to play basketball")
elif height > 6:
    print("You are tall enough to play basketball")
else:
    print ("You are too young and short to play basketball")

We can use "if" to check if the user is old enough and "elif" to check if they are tall enough (this happens only IF they are younger than 18 in this case).

If they are old enough (above 18), the "elif" statement WILL NOT be executed!

If they aren't old enough (below 18), the "elif" statement then checks if they are at least tall enough to play basketball, and if that condition is TRUE, it executes a different piece of code (output: You are tall enough to play basketball).

If they are not old enough or not tall enough, they are too young and short to play basketball.

Simple.

Differences between multiple if and nested if statements

Yes! They are very similar but quite different, kinda. I thought they were just synonyms until a few days ago too but luckily, it is pretty easy to differentiate these two statements.

Multiple "if" and nested "if" statements are similar but not the same thing.

Multiple "if" statements are when you have more than one "if" statement in your code, and each "if" statement checks a different condition. For example, if you want to check if a number is greater than 5 and also if it's even, you can use two "if" statements one after the other. and they have to be executed irrespective of if the first one is TRUE or FALSE.

if number > 5:
    print("The number is greater than 5.")
if number % 2 == 0:
    print("The number is even.")
else:
    print("execute a different action")

Nested "if '' statements on the other hand are when you have MULTIPLE "if" statements nested inside one another.

For example, if you want to check if a person is older than 18 and if they are taller than 6 feet, you can use an "if" statement to check for the age, and inside that "if" statement, you can use another "if" statement to check for the height.

Another code snippet:

if age > 18:
    if height > 6:
        print("You can play basketball!")
    elif height < 6:
        print("You are too short to play basketball.")
else:
    print("You are too young to play basketball.")

The above snippet is a classic example of a nested "if".

For example, if you want to check if a person is older than 18 and if they are taller than 6 feet, you can use an "if" statement to check for the age, and inside that "if" statement, you can use another "if" statement to check for the height.

Note: the nested if won't run unless the "if" statement in which it's nested is first TRUE.

But this is not the case for multiple "if" statements.

"elif" and "nested if" are ways to check multiple conditions in our code, but they work slightly differently.

"elif" is like an alternative helper to "if". It checks if the first "if" statement doesn't find what it was looking for, and then it checks another thing. We can have multiple "elif" statements after one "if" statement to check multiple conditions.

"Nested if" is like having a little "if" inside a bigger "if". We can put one "if" statement inside another "if" statement. The inner "if" statement only runs if the outer "if" statement is TRUE. It's like asking "if this condition A is TRUE, then what is also TRUE?"

Note: "elif" statements come into execution when the "if" it's enclosed in isn't TRUE while for nested "if" statements, the bigger "if" has to be TRUE for it to be executed.

From the indentation point of view, multiple "if" statements are not indented, they are at the same level of the code, while nested "if" statements are indented, meaning that they are inside another "if" statement.

This indentation helps to make the code more readable, and this is one of those little but significant reasons why I love Python.

Now, another code snippet to illustrate nested if:

age = int(input("Enter your age: "))

if age >= 18:
    print("You are an adult.")
    if age >= 21: 
        print("You can legally drink alcohol.")
    else:
        print("You should probably stick to Soda for now!")
else:
    print("You are a minor, you should be drinking milk.")

Note: If you choose not to use an "else" statement for a nested "if" statement, it will not disrupt the code but may not give you the desired outcome.

For example, if you have a nested "if" statement where you check if a person is older than 18 and if they are taller than 6 feet, and you don't use an "else" statement for the nested "if" statement, it will only check if the person is older than 18 and taller than 6 feet.

If they are not taller than 6 feet, the code will not execute any action, it will just continue running the next line of code.

You're still with me, right? Please say, yes.

Best Practices for Using Nested if, Multiple if, and elif statements in Python

When using multiple "if" and "elif" statements in Python, it's essential to be careful to avoid common mistakes, one mistake is using too many "if" statements, which can make the code hard to read and understand.

To write clean and efficient code when using multiple "if", nested "if" and "elif" statements, here are some tips:

  • Use the "elif" statement instead of multiple "if" statements when checking multiple conditions. This will make the code shorter and easier to read.

  • Use proper indentation when nesting "if" and "elif" statements. This will help you keep track of which statements are inside of other statements.

  • Use "else" statements when appropriate. This will make it clear what should happen if none of the "if" or "elif" conditions are met.

  • Be careful when using multiple "if" and "elif" statements, as it can make the code hard to read and understand.

By following these tips, you can write clean and efficient code when using multiple "if" and "elif" statements in Python. Remember, practice makes perfect! So, keep experimenting with these statements and you'll be a pro in no time.

Conclusion

Before I end this article, I want to remind you that if you're starting with Python, the usage of "if" and "elif" statements can feel like a labyrinth, but be calm.

By understanding the basics, the distinctions, and the best practices for using these statements, you'll be able to master the art of decision-making in Python.

But trust me, it WILL take some time. It's something that becomes second nature to you as you use them more and more in your projects. Don't overthink it. Don't memorize. Just practice!

The key to understanding these statements is to experiment, play around and apply them in real-world scenarios, the more you practice, the more you'll get a grip on how these statements work and the more confident you'll become in using them in your next Python project.

So, don't be afraid to dive in and start experimenting!