意外的python函数返回行为

意外的python函数返回行为,python,function,Python,Function,我正在处理一个函数,该函数通常返回1个值,但有时返回2个值,原因与此类似,并注意到一些意外的行为,下面的示例最好地说明了这一点: 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 我希望这

我正在处理一个函数,该函数通常返回1个值,但有时返回2个值,原因与此类似,并注意到一些意外的行为,下面的示例最好地说明了这一点:

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_two为False,则只返回第一个值两次:

testfcn1(False)
(10, 10)

testfcn1(True)
(10, 20)

这种行为是否有理由?

在您的
testfcn1
中,表达式分组为-

(a, (a*2 if return_two else a))           #This would always return a tuple of 2 values.
而不是(你想的那样)-

如果您想要第二组表达式,您必须使用括号,正如我在上面使用的那样


用一个例子来说明区别-

>>> 10, 20 if True else 10
(10, 20)
>>> 10, 20 if False else 10
(10, 10)
>>>
>>>
>>> (10, 20) if False else 10
10
>>> (10, 20) if True else 10
(10, 20)
>>>
>>>
>>> 10, (20 if False else 10)
(10, 10)
>>> 10, (20 if True else 10)
(10, 20)

这是一个简单的运算符优先级问题<代码>返回a,如果返回两个其他a,则返回a*2如果解释为
返回a,(如果返回两个其他a,则返回a*2)
。您应该使用括号来更改优先级

def testfcn1(return_two=False):
    a = 10
    return (a, a*2) if return_two else a
但是你真的想要一个有时返回int,有时返回tuple的函数吗?那会变得一团糟。如果要返回的值的数量可能不同,则始终返回一个元组&让调用方调用元组的
len
方法。此模式的一个可能例外是返回
None
而不是元组,但即使这样,也可以返回空元组。
def testfcn1(return_two=False):
    a = 10
    return (a, a*2) if return_two else a