【问题标题】:Why can't I use return() in a conditional for flow control in Python?为什么我不能在 Python 中的流控制条件中使用 return()?
【发布时间】:2019-05-20 19:25:30
【问题描述】:

考虑这个函数:

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

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

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

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]

而且——除了对简洁/可读性的偏好——对我来说,我不能只在代码中的那个地方执行 return 是没有意义的。 documentation for return 说:

7.6。返回语句

return_stmt ::=  "return" [expression_list]

return 只能在语法上嵌套在函数定义中, 不在嵌套类定义中。

如果存在表达式列表,则对其求值,否则为无 替换。

return 将当前函数调用与表达式列表(或 无)作为返回值。

当 return 使用 finally 将控制权从 try 语句中传递出去时 子句,该 finally 子句在真正离开之前执行 功能。

在生成器函数中,return 语句表示 生成器完成并将导致 StopIteration 被引发。这 返回值(如果有)用作构造的参数 StopIteration 并成为 StopIteration.value 属性。

在异步生成器函数中,一个空的返回语句 表示异步生成器已完成并将导致 要引发的 StopAsyncIteration。非空返回语句是 异步生成器函数中的语法错误。

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

【问题讨论】:

标签: python return conditional-operator


【解决方案1】:

这里的区别是“语句”和“表达式”。 A if B else C 表达式要求 A、B 和 C 是表达式。 return 是一个语句,因此它在那里不起作用 - 与 breakraise 相同。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 2011-03-06
      • 2012-03-26
      • 1970-01-01
      • 2020-01-07
      • 2023-03-21
      相关资源
      最近更新 更多