Swapping of 2 numbers in Python

Vishnuvarshan P
1 min readFeb 13, 2023

--

Approach 1 : Using a temporary variable

First we have to get the 2 numbers as a input

num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))

After that, we need to assign the value of num1 with a temp variable, and then assign the value of num2 to num1 and assign the value of temp to num2.

print("Before Swapping : ",num1,num2)
temp = num1
num1 = num2
num2= temp
print("After Swapping : ",num1,num2)

Now, the values has been swapped.

Output:

Enter num1: 10

Enter num2: 20

Before Swapping : 10 20

After Swapping : 20 10

Approach 2: Without using temp variable

It is quite straight forward.

print("Before Swapping : ",num1,num2)
num1,num2 = num2,num1
print("After Swapping : ",num1,num2)

Here, the values are swapped because before seeing the variables, python looks to the values first and then assigns it to the variables.

Output:

Enter num1: 10

Enter num2: 20

Before Swapping : 10 20

After Swapping : 20 10

Hence, the swapping of 2 variables in python is completed.

--

--