Should we always include an else for every if statement?

Question

In Python, is it necessary, or best practice, to include an else for every if statement?

Answer

No, an else statement is neither necessary for every if statement nor is it really “best practice” to always include one for each.

For instance, your program may only need to do something if a condition is True, but nothing otherwise. In this case, you would only need an if statement and no else statement.

It is a choice that can be very dependent on the programmer and the nature of the program, and how it is decided what should happen if a condition is not met. If not needed, an else does not have to be added. In fact, if nothing else should happen, excluding an else can keep the code a few lines shorter.

23 Likes

Hello. For example, in PHP we try to eliminate “else” from our code! Check this article. It will explain clearly what the problem is with “else”. Stop using “else”. It can sounds like I’m asking you to… | by Kyle K | Medium

2 Likes