Python Program to Swap Two Variables

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

For all the practice Videos and Explanations on Python please click over here. Python Practice Series.

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 is the exchanging of the values of the two 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.

So what we will do. We will take the third container. Call it C. And then we will put the content of  A into C. Now we will put container B’s content into A. Finally the content of container C into B.

You see the contents are swapped. Let’s implement the same logic in programming.

Video Explanation to Swapping of Two Numbers in Python

Above Video content of Swapping of Two Numbers in Python.

Code: Swapping of Two Numbers in Python

The above video explains only one method to the Swapping Two Numbers in Python. But you can find source code and explanation of different methods over here

Method 1: Swapping of Two Numbers using temp variable in Python

Let’s write a program which Swap Two Number.

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

Now you see we got the output 20 and 10.

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

Method 2: Swapping of Two Numbers using temp variable in Python

Source Code with Explanation

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

x = x+y
y = x-y
x = x-y

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

Output

Enter the Value of x: 5
Enter the Value of y: 6
Values after swapping x= 6 y= 5

Method 3: Swapping of Two Numbers using Accepting number using input statement in Python

Source Code with Explanation

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

x,y = y,x

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

Output

Enter the Value of x: 50
Enter the Value of y: 60
Values after swapping x= 60 y= 50

Facebook Comments
(Visited 1 times, 1 visits today)

Leave A Comment

Your email address will not be published. Required fields are marked *