
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.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer