Swap two variables in Python

Swap two numbers using third variable

Swap two variables 

Swapping two variables means swapping of the data stored in one variable to another variable and vice-versa. Swap two variables in Python can be done in many ways , few of them is using third variable , without using third variable , and by functions .
Lets see about swapping two variables by using third variable. 

To see swapping of two variables without using third variable  click here

Sample input: a=12 b=34
Sample output: a=34 b=12

Working of Swap two variables in Python

  • Step 1: Read first variable
  • Step 2: Read second variable
  • Step 3: Store data of first variable to some temporary variable
  • Step 4: Now move data of second variable to first variable
  • Step 5: We lost the data of first variable now as it is updated with another value. But we stored that in third variable
  • Step 6: Now move the data of third variable to second variable .
  • Step 7: Print data 

Let a=12 and b=34 
temp=a (temp=12)
a=b         (a=34)
b=temp (b=12)

Python code:

# Swap two variables in Python
a=int(input(“Enter value : “))
b=int(input(“Enter value : “))
print(“Before swapping a :”,a)
print(“Before swapping b :”,b)
#logic to swap using third variable 
temp=a
a=b
b=temp
print(“After swapping a becomes :”,a)
print(“After swapping b becomes :”,b) 
Enter value : 12
Enter value : 34
Before swapping a : 12
Before swapping b : 34
After swapping a becomes : 34
After swapping b becomes : 12
Swap two variables in Python