Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swap function output is different from what expected [duplicate]

I think the output should be x = 5, y = 3. But, when I tried executing it in jes it shows that x=3 and y=5.

My swap function is as follows:

def swap (x,y):    
    temp=x
    x=y
    y=temp

And from my driver function I call swap():

def driver():    
    x=3
    y=5
    swap(x,y)
    print x
    print y

I want to know why isn't the output as expected?

like image 470
Amiya Avatar asked Mar 16 '26 19:03

Amiya


2 Answers

Well this is not a big issue in python you can return multiple values like try this snippet it might help you.

def swap(a,b):
   return (b,a)

def driver(x,y):
    print "Previous x=",x,"y=",y
    x,y = swap(x,y)
    print "Now x=", x, "y=",y

driver(3,5)
like image 52
Chitrank Dixit Avatar answered Mar 18 '26 09:03

Chitrank Dixit


As other answers have suggested, this really doesn't require functions. Since you have decided to use them though, you might as well try and understand a bit more about scopes.

In order to retain the swapped values you need to return them or else they get lost after the execution of swap():

def swap (x,y):
    temp=x
    x=y
    y=temp
    return x, y  # must return the swapped values.

Then, in the function where you call swap() you assign the returned values to the variables that you swapped:

def driver():
    x=3
    y=5
    x, y = swap(x,y)  # re-assign values
    print x
    print y

Running driver() now will give you the swapped value:

5
3

This happens because in the function swap() the variables x and y you pass as arguments are treated as local to that function, only swap can see their value. If you don't return this value back, it is lost and forgotten.

like image 22
Dimitris Fasarakis Hilliard Avatar answered Mar 18 '26 08:03

Dimitris Fasarakis Hilliard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!