【发布时间】: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。非空返回语句是 异步生成器函数中的语法错误。
在我看来,该定义中的任何内容都不会排除我正在尝试的用法。这里有什么我不明白的地方吗?
【问题讨论】:
-
我想指出
if not condition1: return "condition1 was not met"可以将所有内容放在一行上,这可能适合您所需的流程 -
是的,你错过了docs.python.org/3/reference/expressions.html#boolean-operations,通过条款点击自己,即。 docs.python.org/3/reference/…, ..docs.python.org/3/reference/…, ..., docs.python.org/3/reference/…, .. 当你到达docs.python.org/3/reference/… 时,你会明白你不能在那里放一个回报,因为语法不允许它;- )
标签: python return conditional-operator