Skip to main content

Write a Function To Swap Values - Python

· One min read
Kaustubh Kulkarni

Let us see program to Function To Swap Values,

Using Temporary Variable

file.py
# method Using Temporary Variable
def swap(a,b):
temp=a
a=b
b=temp
return a,b

Output

file.vb
print(swap(7,3))
>> (3,7)

Direct Method

file.vb

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

Output:

file.vb
print(swap(3,7))
>>(7,3)

Without Using Temporary Variable

file.vb
def swap(a,b):
a=b+a
b=a-b
a=a-b
return a,b
file.vb
print(swap(5,7))
>>(7,5)