当函数中的每个路径都有一个return语句时,不使用else语句是错误的吗?

2024-04-27 04:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试更好地设计我的代码,并确保它尽可能可读。你知道吗

跳过else而只得到一个回报会被认为是不好的做法吗?你知道吗

例如:

if x == 1:
    return True
return False

而不是:

if x == 1:
    return True
else:
    return False

Tags: 代码falsetruereturnifelse
2条回答

我总是直接返回时,它不影响。你知道吗

我没有找到这方面的参考资料,但这是我的设想

因为有些时候你可能不得不做

for spam in bacon:
    if spam == egg:
        return spam

但是,如果要避免在if语句中返回,则必须执行以下操作:

return_value = None

from spam in bacon:
    if spam == egg:
        return_value = spam
        break

 return return_value

结果与执行结果完全相同,但只添加了3行不相关的行,因此我最终认为,当发生这种情况时,我总是使用相同的规则:直接返回。你知道吗

问题是不要对for/if/return太深入,但这并不是真正的问题。你知道吗

这两种样式都有效,python样式指南(PEP 8)没有为这两种样式指定首选项。你知道吗

无论你决定用哪一种,都要坚持。这将导致代码更易于阅读。你知道吗

PEP 8

[…] code is read much more often than it is written. […] As PEP 20 says, "Readability counts".

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

Programming recommendations下:

Yes:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)

相关问题 更多 >