Write a python program to swap two numbers.

There are three method to swap the value of two numbers in the python :

 Method 1:-

a=int(input(“a=”))
b=int(input(“b=”))
print(“Values before swapping=”,“a=”,a,“b=”,b)
temp=a
a=b
b=temp
print(“Values after swapping=”,“a=”,a,“b=”,b)
Output:-

a=2
b=3
Values before swapping
a= 2 b= 3
Values after swapping
a= 3 b= 2


Method 2:-
a=int(input(“a=”))
b=int(input(“b=”))
print(“Values before swappingn”,“a=”,a,“b=”,b)
a,b=b,a
print(“Values after swappingn”,“a=”,a,“b=”,b)
output:-

a=2
b=3
Values before swapping
a= 2 b= 3
Values after swapping
a= 3 b= 2


Method 3:-

a=int(input(“a=”))
b=int(input(“b=”))
print(“Values before swappingn”,“a=”,a,“b=”,b)
a=a+b
b=a-b
a=a-b
print(“Values after swappingn”,“a=”,a,“b=”,b)
 Output:-

a=2
b=3
Values before swapping
a= 2 b= 3
Values after swapping
a= 3 b= 2


One thought on “Write a python program to swap two numbers.

Leave a Reply

Your email address will not be published.