意外的python函数返回行为

2024-09-30 16:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个函数,该函数通常返回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)

这种行为有什么道理吗?你知道吗


Tags: 函数falsetrue示例returnifdef原因
2条回答

testfcn1中,表达式分组为-

(a, (a*2 if return_two else a))           #This would always return a tuple of 2 values.

而不是(你想的那样)-

(a, a*2) if return_two else a             #This can return a tuple if return_two is True otherwise a single value `a` .

如果你想要第二组表达式,你必须使用括号,就像我在上面使用的那样。你知道吗


举例说明区别-

>>> 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)

这是一个简单的运算符优先级问题。return a, a*2 if return_two else a如果解释为return a, (a*2 if return_two else a)。您应该使用括号来更改优先级。你知道吗

def testfcn1(return_two=False):
    a = 10
    return (a, a*2) if return_two else a

相关问题 更多 >