Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, should I use else after a return in an if block? [closed]

First, I couldn't find an answer to this in PEP 8. That doesn't mean it isn't in there. Feel free to point me at it.

Which style do you prefer?

The first one:

if spam:
    # Do stuff.
    return eggs
else:
    # Maybe do other stuff.
    return parrots

or the second one:

if spam:
    # Do stuff.
    return eggs
# Maybe do other stuff.
return parrots

2 Answers

It depends, if you would return parrots, when you do not return eggs, then the first one is more clear. But if you are trying to catch an error or something like that, the second one is better.

like image 118
Omid Kamangar Avatar answered Sep 12 '25 10:09

Omid Kamangar


The first one!

Explicit is better than implicit.

like image 45
Danyal Raja Avatar answered Sep 12 '25 11:09

Danyal Raja