Reputation: 1
Why does this python code not swap the numbers?
def swap(x, y):
'''THe swap function'''
print("INSIDE")
temp = x
x = y
y = temp
#Driver_code
x = 2
y = 3
swap(x, y)
print(x)
print(y)
Upvotes: 0
Views: 72
Reputation: 682
The swap function is not returning values
def swap(x, y):
'''THe swap function'''
print("INSIDE")
temp = x
x=y
y= temp
return x,y
#Driver_code
x = 2
y = 3
x,y=swap(x, y)
print(x)
print(y)
Here, you assign the returning values to x and y.
Upvotes: 0
Reputation: 577
Because the swap is inside the function.
You're swapping the values of the function parameters x
and y
, which are different from the x
and y
that are used below.
Just do this:
x, y = y, x
Upvotes: 0
Reputation: 59
In the Swap function add this one line:
global x,y;
The problem is when you are calling the swap() function it is making its own variable x and y, not using the global variable x and y
Upvotes: 1