首页 > 解决方案 > python函数条件返回

问题描述

使用条件返回时,如果您尝试从函数返回多个值,则函数的行为与实际返回值有关。

def test_function(x,y, diagnostic:bool=False):
    w = x*y
    z = []
    if diagnostic: 
        z = [w,w*2]
    return z, w if diagnostic else w

print(test_function(3,4)) # output tuple ([],12)

# lets switch order of the return from z,w to w,z

def test_function(x,y, diagnostic:bool=False):
    w = x*y
    z = []
    if diagnostic: 
        z = [w,w*2]
    return w,z if diagnostic else w

print(test_function(3,4)) # output tuple (12,12) 

# lets try retun the diagnostic value itself to see what function things is happening

def test_function(x,y, diagnostic:bool=False):
    w = x*y
    z = []
    if diagnostic: 
        z = [w,w*2]
    return diagnostic if diagnostic else w

print(test_function(3,4)) # returns 12, so diagnostic is retuning false

# rewrite conditional to "if not"
def test_function(x,y, diagnostic:bool=False):
    w = x*y
    z = []
    if diagnostic: 
        z = [w,w*2]
    return w if not diagnostic else w,z

print(test_function(3,4)) # returns (12, [])

标签: python

解决方案


问题是运算符优先级:,优先级低于... if ... else ...,所以你实际写的是 like return z, (w if diagnostic else w),或者在第二个函数中,它是 like return w, (z if diagnostic else w)

对此的提示是,diagnosticFalse您仍在返回一对值。

对于你想要的行为,你应该写return (z, w) if diagnostic else w. 请注意,此处的括号不需要使其成为元组 - 无论哪种方式,它都是一个元组 - 括号用于指定优先级。


推荐阅读