Python Forum
I am trying to swap two variables with a Function.... - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: I am trying to swap two variables with a Function.... (/thread-16532.html)



I am trying to swap two variables with a Function.... - Jeff_Waldrop - Mar-04-2019

Obviously, I am a newbie and I have something wrong....! Could you help me see what my error is?

Thanks,

Jeff

-------------------------
a = 100
b = 200

def swap(a, b):
    a = x
    b = y
    x = z
    b = x

    return




swap (a, b)

print (a)  #Trying to get 200 

print (b)  #Trying to get 100

OK, so that code is wrong. I apologize for posting.

ADMIN, you can delete. I am not allowed to delete the original post.


RE: I am trying to swap two variables with a Function.... - ichabod801 - Mar-04-2019

You can't put a name on the right side of an assignment (=) until it's been on the left side of an assignment. Until it's on the left side, it doesn't exist. So x and y are going to cause name errors.

More generally, you need to store one of the values so you can access it after you have overwritten it with the other value.

I'm assuming this is homework, because there's an easier way to do this in Python.


RE: I am trying to swap two variables with a Function.... - walkinrain - Mar-04-2019

The parameters are exchanged within the function and do not affect the value of the variable with the same name outside the function.
example:
a = 100
b = 200
 
def swap(a, b):
    x=a
    a=b
    b=x
    # The above code is equivalent to  "a, b=b, a"
    return a,b

def swap2():
    global a,b
    a,b=b,a
x,y = swap (a, b)
 
print (f"a={a},b={b},x={x},y={y}")
swap2()
print (a,b)
output:
Output:
a=100,b=200,x=200,y=100 200 100



RE: I am trying to swap two variables with a Function.... - DeaD_EyE - Mar-04-2019

The swapping with temporary variables is error prune.
Here an example with swapping:
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
        yield(a)
And now the complicated version:
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        x = a + b
        a = b
        b = x
        yield(a)
Also a function should never change values outside of the function. This leads into an unexpected behavior. You can do this with short code.
In bigger projects, this is the opening of hell's gates. You deserve what you get.

In earlier programming languages there was a big difference between functions and procedures. A function is just something to do a calculation without affecting the outside world. A procedure was affecting the outside world, like printing on a terminal or printer.


RE: I am trying to swap two variables with a Function.... - Jeff_Waldrop - Mar-04-2019

Thanks, all.

This is good, learned a couple of things here....!

:)