python - 意外的 python 函数返回行为

标签 python function

我正在开发一个通常返回 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_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.

而不是(你认为的那样)-

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

关于python - 意外的 python 函数返回行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32654860/

相关文章:

javascript - JQuery Ajax 用 Jquery 函数替换项目

c - 星号和函数名之间的空格

python - Pandas 有条件创建新的数据框列

python - 在 bool 列表中获取 True 值的索引

python - 5D 卡尔曼滤波器不起作用,我们不确定哪里出了问题

python - 从日期列表生成元组列表(年、月、days_in_month、full_month)

python - 如何从 Python 制作 .app 包含图像文件

javascript - 绑定(bind)函数不返回对象的引用

javascript - 简单例子中call、apply、bind的比较

c# - 为什么我不能在fixed语句中使用extern函数?