在Python中,我应该在if块中返回后使用else吗? [英] In Python, should I use else after a return in an if block?

查看:298
本文介绍了在Python中,我应该在if块中返回后使用else吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我在 PEP 8 中找不到答案。这并不意味着它不在那里。

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.

您最喜欢哪种风格?

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

第二个

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.

这篇关于在Python中,我应该在if块中返回后使用else吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆