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

When every path in a function has a return statement is it wrong to not use an else statement?

我一直在努力改进我的代码样式并尽可能确保其可读性。

跳过 else 而只使用 return 会被认为是不好的做法吗?

例如:

if x == 1:
    return True
return False

而不是:

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

两种样式均有效,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)

我总是return不影响的时候直接s。

我没有找到相关参考,但这是我的设想

因为有时候你可能不得不做一些事情,比如

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

但是如果你想避免在 if 语句中使用 returning 你将不得不这样做:

return_value = None

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

 return return_value

结果与执行完全相同,但只添加了 3 条不相关的行,所以我最终认为发生这种情况时我总是使用相同的规则:return 直接 .

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