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

Table of Contents

### 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.

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

### Video Explanation of Swapping of Two Numbers in Python

## Program to Swap Two Numbers in Python

The above video explains only one method for 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 Numbers.

#### Source Code

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 outputs 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

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

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
```