开发者

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

开发者_C百科 As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

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


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.


The first one!

Explicit is better than implicit.


The second one! Less is more, and more is better.


It doesn't really matter. If you really need reasons for picking one, use the one that best conveys the reasons behind the code. The first one if both cases are somehow similar or equally important. The second one if you usually return parrots but eggs is a special case.


The second one. The same applies not only to return but also to break and continue statements. The else and the consequent indentation are eye-irritating and a waste of space.


Neither!

if spam:
    # Do Stuff
    result= eggs
else:
    # Maybe do other stuff
    result= parrots
return result


I think it depends on the "do stuff" part. Both are acceptable.


I don't know python, but I do :

return spam if eggs else parrots

Edit : I didn't notice the Do stuff part. In that case, I would create another method or function (whatever it is called in python) for each branch.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜