我正在处理一个函数,该函数通常返回1个值,但有时返回2,原因与this post类似,我注意到一些意外的行为最好用这个示例来说明:
def testfcn1(return_two=False):
a = 10
return a, a*2 if return_two else a
def testfcn2(return_two=False):
a = 10
if return_two:
return a, a*2
return a
我希望这两个函数的行为方式相同。testfcn2按预期工作:
testfcn2(False)
10
testfcn2(True)
(10, 20)
但是,testfcn1总是返回两个值,如果return\u two为False,则只返回第一个值两次:
testfcn1(False)
(10, 10)
testfcn1(True)
(10, 20)
这种行为有什么道理吗?你知道吗
在
testfcn1
中,表达式分组为-而不是(你想的那样)-
如果你想要第二组表达式,你必须使用括号,就像我在上面使用的那样。你知道吗
举例说明区别-
这是一个简单的运算符优先级问题。
return a, a*2 if return_two else a
如果解释为return a, (a*2 if return_two else a)
。您应该使用括号来更改优先级。你知道吗相关问题 更多 >
编程相关推荐