为什么我不能在 Python 中的流量控制条件中使用 return()?

Why can't I use return() in a conditional for flow control in Python?

考虑这个函数:

def parity(num):
    num % 2 == 0 and return "that is even"
    return "that is odd"

该函数的第一行是语法错误(我使用的是 v 3.7.3)。为什么?看来你应该可以 "return" 从任何你想去的地方。

注意:我意识到在这种特定情况下我可以使用

return "that is even" if num % 0 == 0 else "that is odd"

那不是我的问题。我的问题是它更紧凑,更容易阅读流程,如果你写:

condition 1 or return "condition one was not met"
condition 2 or return "condition two was not met"
condition 3 or return "contition three what not met"
[rest of the function goes here]

比:

   if not condition 1:
        return "condition one was not met"
   if not condition 2:
        return "condition two was not met"
   if not condition 3:
        return "condition three was not met"
   [rest of the function goes here]

并且——除了对 brevity/readability--it 的这种偏好之外,对我来说根本没有意义,我不能只在代码的那个地方执行 return。 documentation for return 表示:

7.6. The return statement

return_stmt ::=  "return" [expression_list]

return may only occur syntactically nested in a function definition, not within a nested class definition.

If an expression list is present, it is evaluated, else None is substituted.

return leaves the current function call with the expression list (or None) as return value.

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

In an asynchronous generator function, an empty return statement indicates that the asynchronous generator is done and will cause StopAsyncIteration to be raised. A non-empty return statement is a syntax error in an asynchronous generator function.

在我看来,该定义中的任何内容都不排除我正在尝试的用法。有什么地方我不明白吗?

这里的区别是"statements"和"expressions"。 A if B else C 表达式要求 A、B 和 C 为表达式。 return 是一个声明,因此它在那里不起作用 - 与 breakraise 相同。

原因就在它的名字里。这是一个 语句 。语句不同于 表达式 。您可以将多个表达式组合成一个更大的表达式。声明不是这样;语句的定义特征是它不能成为更大表达式的一部分,部分原因是它的行为不同(通常控制流),部分原因是它不会产生一个值可以组成一个更大的表达式。