Ritesh Yadav
last year
Riteshcountry asked

Why should we use the "else" statement when the output is same when we use two "if" statements?

Abhay Jajodia
Expert
last year
Abhay Jajodia answered

Using else is helpful even if you might get the same output using if twice. Here's why:

When you use an if statement followed by an else, you're creating a clear and organized structure that makes your code easier to read and understand.

The else ensures that if the initial if condition isn't met, a secondary block of code is executed by default.

Let's break it down with an example of checking the weather:

weather = input("What's the weather? ")

The if statement checks if the weather is "raining":

If weather == "raining":
    print("Carry an umbrella.")

The else comes in for every other possibility:

else:
   print("Enjoy the day.")

This way, the program handles multiple possibilities with just a few lines. If you used two if statements instead, like this:

if weather == "raining":
   print("Carry an umbrella.")

if weather != "raining":
   print("Enjoy the day.")

The logic still works, but it's less efficient and can make the code harder to maintain, especially as your programs grow.

The compact if...else not only neatly addresses both outcomes, but also signifies clear alternate paths in decision-making.

Python
This question was asked as part of the Getting started with Python course.