Q. Following code intends to swap the values of two variables through a function, but upon running the code, the output shows that the values are swapped inside the switch() function but back again in main program, the variables remain un-swapped. What could be the reason? Suggest a remedy.


def switch(x, y):
    x, y = y, x
    print("inside switch :", end = ' ')
    print("x", x, "y=", y)

X = 5
y = 7
print("x", x, "y=", y)
switch(x, y)
print("x", x, "y=", y)


Answer :-

The reason for un-reflected changes in the main program is that although both main program and switch() have variables with same names i.e., x and y, but their scopes are different as shown in the adjacent figure.
The scope of x and y switch() is local. Though they are swapped in the namespace of switch() but their namespace is removed as soon as control returns to main program. The global variables x and y remain unchanged as switch() worked with a different copy of values not with original values.

The remedy of above problem is that the switch() gets to work with global variables so that changes are made in the global variables. This can be done with the help of global statement as shown below:

def switch(x, y):
    global x, y
    X, y = y, X
    print("inside switch :", end = ' ')
    print("x", x, "y =", y)

X = 5
y = 7
print("x", x, "y =", y)
switch (x, y)
print("x", x, "y =", y)

Now the above program will be able to swap the values of variables through switch(). (Though, now passing parameter is redundant.)

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post