mso*_*uth 0 python return conditional-operator
考虑以下功能:
def parity(num):
num % 2 == 0 and return "that is even"
return "that is odd"
Run Code Online (Sandbox Code Playgroud)
函数的第一行是语法错误(我正在使用3.7.3版)。为什么?似乎您应该可以从任何地方“返回”。
注意:我意识到在这种特定情况下,我可以使用
return "that is even" if num % 0 == 0 else "that is odd"
Run Code Online (Sandbox Code Playgroud)
那不是我的问题。我的问题是,如果您编写以下代码,它会更紧凑且更容易阅读该流程:
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]
Run Code Online (Sandbox Code Playgroud)
比:
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]
Run Code Online (Sandbox Code Playgroud)
而且-除了对简洁/可读性的偏爱之外-对我而言,我不能仅仅在代码中的那个位置执行返回就完全没有意义。该退货的文件说:
7.6。退货声明
Run Code Online (Sandbox Code Playgroud)return_stmt ::= "return" [expression_list]return只能在语法上嵌套在函数定义中,而不能在嵌套的类定义中。
如果存在表达式列表,则将对其求值,否则将用None代替。
return使当前函数调用以表达式列表(或None)作为返回值。
当return将控制通过带有finally子句的try语句传递出去时,将在真正离开该函数之前执行finally子句。
在生成器函数中,return语句指示生成器已完成,并将引起StopIteration升高。返回的值(如果有)用作构造StopIteration的参数,并成为StopIteration.value属性。
在异步生成器函数中,空的return语句表示异步生成器已完成,并且将引发StopAsyncIteration。非空return语句是异步生成器函数中的语法错误。
在我看来,该定义中的任何内容都无法排除我正在尝试的用法。这里有我不理解的东西吗?