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 swapping\n","a=",a,"b=",b)
a,b=b,a
print("Values after swapping\n","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 swapping\n","a=",a,"b=",b)
a=a+b
b=a-b
a=a-b
print("Values after swapping\n","a=",a,"b=",b)
Output:-
a=2
b=3
Values before swapping
a= 2 b= 3
Values after swapping
a= 3 b= 2
1 Comments
Excellent
ReplyDelete