Write a function in python that exchanges data using swap function to interchange the given two numbers .
Write a function in Python that exchanges data using swap function to interchange the given two numbers .
In Python a function cannot change the caller's integer variables directly, so the swap function returns the two values in reverse order and the caller assigns them back.
def swap(a, b):
temp = a # store first value
a = b # copy second into first
b = temp # copy stored value into second
return a, b
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Before swap: x =", x, "y =", y)
x, y = swap(x, y)
print("After swap: x =", x, "y =", y)
Sample run
Enter first number: 10
Enter second number: 25
Before swap: x = 10 y = 25
After swap: x = 25 y = 10
How it works. Inside swap, a temporary variable holds the first value while the second is copied over. Python integers are immutable, and the parameters a and b are local names, so the function returns a tuple (a, b); the statement x, y = swap(x, y) unpacks it into the original variables.
The body of the function can also be written in one line using tuple packing: return b, a.
Log in or create a free account to answer this question.