Python Program to Swap Two Numbers | without using temporary variable & with using temporary variable
Swapping of two numbers means, first number becomes second and second number becomes first. For example, if user enters any two number say 5 and 10. And let's suppose the two variables say a and b holds these two numbers. That is, a=5 and b=10. Then after swapping it will be like a=10 and b=5.
In this example, you will learn to swap two variables by using a temporary variable and, without using a temporary variable.
Python Program to Swap Two Numbers without using temporary variable:
a = 5
b = 10
print("Before swap a=",a,"b=",b)
a = a + b
b = a - b
a = a - b
print("After swap a=",a,"b=",b)
Output:
Before swap a= 5 b= 10
After swap a= 10 b= 5
Python Program to Swap Two Numbers with using temporary variable:
a=5
b=10
print("Before swap a=",a,"b=",b)
temp=a
a=b
b=temp
print("After swap a=",a,"b=",b)
Output:
Before swap a= 5 b= 10
After swap a= 10 b= 5
No comments: