Swapping of Two Numbers using temp variable in Python

Swapping of Two Numbers using temp variable in Python

In this blog, we will be explaining how to write different programs to swap two numbers. 

What is Swapping?

So precisely what is swapping? Swapping means taking the value from variable a to variable b and vice versa.

In another word, ” swapping means replacing values of a variable with other variables. “

For a moment, forget about programming. Just assume we have two containers A and B. And now we need to take the content of container A into container b and vice versa.

For all the practice Videos and Explanations on Python See Here Python Practice Series.

Program to Swapping of Two Numbers using temp variable in Python

Let’s write a program that Swaps Two Numbers.

Source Code with Explanation

x = int(input("Enter the Value of x:"))
y = int(input("Enter the Value of y:"))

temp = x
x = y
y = temp

print("Values after swapping x=",x,"y=",y)


Enter the Value of x: 10
Enter the Value of y: 20
Values after swapping x= 20 y= 10

To write a swapping program in python, a temporary variable is used as the temporary storage. 

The first content of the variable “x” goes into a temp variable

Then the content of variable “y” in a variable

Then the content of the temp variable goes to y.

If you print the result the value is swapped.

If you want to learn python programming you can refer to this Python online Course with Certification. It’s easy to understand and meant for beginners who have no background in programming.