Code Point
September 10, 2010, 07:00:41 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
News: Geshi Sintax Hilighting Mod Installed. Tens of languages available.
 
   Home   Help Search Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: Return more than one value from a function  (Read 2616 times)
Brussely
Jr. Member
*

Karma: 0
Offline Offline

Posts: 2


« on: September 13, 2006, 09:54:16 PM »

I want my function to return more than one value. Is it possible?

Code
>>> def f(x):
...    power = x ** 2
...    sqr = x ** (1.0 /2)
...    return sqr
...    return power
...
>>> f(2)
1.4142135623730951

But it is only returning the square root.  Huh
Logged
Alter Lobo
Global Moderator
Jr. Member
*****

Karma: 10
Offline Offline

Posts: 65


« Reply #1 on: September 13, 2006, 10:05:24 PM »

The function will exit at the first return it finds. So in your example the first return returns sqr and exits the function never reaching the second return.

You can return as many values as you want in a single return using a tuple. Just separate them with a comma:

Code
def f(x):
  power = x ** 2
  sqr = x ** (1.0 /2)
  return sqr, power
 
x = 2
sqr, power = f(x)
print "The square root of", x, "is", sqr
print "The power of", x, "is", power

Notice how the values are unpacked into both variables when the function returns.
Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!