Swapping of Two Numbers in Python Using Temp Variable

Swapping of Two Numbers in Python Using Temp Variable
(Last Updated On: 12/09/2022)

In this blog, we will be explaining how to write swapping of two numbers in python using the temp variable.

What is Swapping?

Swapping means taking the value from variable a to variable b and vice versa. In other words, ” 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 Swap Two Numbers in Python using temp variable

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)
Output
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.

If you still do not understand, watch this video.