如何在函数中返回可选参数

sux*_*ide 5 python return function

我希望有一个函数返回我给它的参数的多个结果函数。

我已经尝试过谷歌搜索等,但没有任何运气

例如:

def function(x, i_add = False):
    if i_add == True:
        y = x+1

    return x, (Y)?
Run Code Online (Sandbox Code Playgroud)

给出的例子我想要的结果是:

function(3) -> 3
function(3, True) -> 3, 4
function(3, False) -> 3
Run Code Online (Sandbox Code Playgroud)

我正在使用 python 2.7

Dea*_*ool 1

您可以返回所需数量的值,如果您返回多个值,则返回tuple一个值,如果返回一个值,则仅返回一个值

def function(x, i_add = False):
  if i_add == True:
     return x,x+1
  else:
     return x


re=function(10,True)  # or a,b=function(10,True)
print(type(re))    #tuple  (10,11)
r=function(10,False)
print(type(r))     # int      10
Run Code Online (Sandbox Code Playgroud)