Monday, February 22, 2010

Returning multiple values from a Python function

I was working on my Python scripts. Then I came to a point where I require more than 1 value to be returned from a function that I wrote. Usually, functions in Python can only return one thing, but the one thing can be a collection of items - tuple. The returned values can be broken down into a bunch of variables:

# Create a function as below, with three returns:
def addme(num):
v1 = num + 15
v2 = num - 10
v3 = num * 2
return v1,v2,v3;

# Running the function:

main = addme (15)
sA, sB, sC = addme (15)

#By printing main, main will be equal to (30,5,30):

print main

#By printing main[0], main[1] and main[2], you'll get individual values of 30, 5 and 30 respectively:
 print main[0]
print main[1]
print main[2]

#Or, another way would be printing sA, sB and sC; you'll get 30, 5 and 30 respectively as well:

print sA
print sB
print sC

No comments:

Post a Comment