How can i return more than one value from a function to more than one variable

D

dec135

basically what I wanna do is this :

x = 4
y = 7
def switch (z,w):
***this will switch z to w and vice verca***
c= z
z=w
w=c
print 'Now x =', w, 'and y = ' , z
return w
x = switch(x,y)

How am I supposed to do so I can return also a value to the variable y WITHOUT printing 'Now x =', w, 'and y = ' , z a second time ?

thanks in advance
 
R

Rick Johnson

basically what I wanna do is this :
x = 4

y = 7
def switch (z,w):
***this will switch z to w and vice verca***
c= z
z=w
w=c
print 'Now x =', w, 'and y = ' , z
return w
x = switch(x,y)

If your intent is to swap the values of two variables (which
is really rebinding the names only) then why do you need a
function at all when you could explicitly swap the values
yourself? What gain would a function give you -- even if you
could do it?
 
S

Simon Hayward

basically what I wanna do is this :
x = 4
y = 7
def switch (z,w):
***this will switch z to w and vice verca***
c= z
z=w
w=c
print 'Now x =', w, 'and y = ' , z
return w
x = switch(x,y)

How am I supposed to do so I can return also a value to the variable y
WITHOUT printing 'Now x =', w, 'and y = ' , z a second time ?

thanks in advance

Using multiple assignment.

# Swap values
x, y = 4, 7
y, x = x, y

Or to keep this in a function, return a tuple and assign from that:

def switch(x, y):
return y, x

x, y = switch(x, y)
 
G

Gary Herron

basically what I wanna do is this :

x = 4
y = 7
def switch (z,w):
***this will switch z to w and vice verca***
c= z
z=w
w=c
print 'Now x =', w, 'and y = ' , z
return w
x = switch(x,y)

How am I supposed to do so I can return also a value to the variable y WITHOUT printing 'Now x =', w, 'and y = ' , z a second time ?

thanks in advance

I don't' understand the question, but if you are just trying to exchange
the values of x and y, this will do:

x,y = y,x


If you want a function to return several values to several variables, try:

def fn(...):
# calculate a and b
return a,b

p,q = fn(...)

All these comma-separated sequences are tuples, often written with
parentheses as (x,y)=(y,x) and (p,q)=fn(...), but as here, the
parentheses are often not necessary.

Gary Herron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top