5

I'd love to have a function return a number of results function of the parameters I give it.

I've already tried googling etc but didn't have any luck

For example:

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

    return x, (Y)?

Given the example the results I'd like to have are:

function(3) -> 3
function(3, True) -> 3, 4
function(3, False) -> 3

I'm on python 2.7

4 Answers 4

3

With simple condition on return statement:

def function(x, i_add = False):
    return (x, x+1) if i_add else x
Sign up to request clarification or add additional context in comments.

1 Comment

This is exaclty what I was searching for! Thanks :)
1

You can return as many you need, If you return multiple values it will be tuple and if you return one value it will be just value

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

1 Comment

As above: exactly what I was searching for.
1

You can do this using a Tuple:

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

var1, var2 = function(3, True)

print(var1)
print(var2)

you can find more on geeksforgeeks: https://www.geeksforgeeks.org/g-fact-41-multiple-return-values-in-python/

Comments

0

A DRY (Don’t repeat yourself) version using tuple concatenation

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

Useful, if you have many default return arguments (e.g. u,v,w,x,y,[z]).
It always returns a tuple.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.