Python Swap Two Variables

In computer programming, swapping two variables specifies the mutual exchange of values of the variables. It is generally done by using a temporary variable.

See more: Python Solve Quadratic Equation

For example, before swapping: var_1 = 1  and var_2 = 5. After swapping, var_1 = 5 and var_2 = 1.

Python Swap Two Variables Using Temporary Variable

We use a temporary variable temp to store the value of var_1, then assign the value of var_2 to var_1. Finally, we assign the value of temp to var_2.

var_1 = input('The fisrt variable = ')
var_2 = input('The second variable = ')

temp = var_1
var_1 = var_2
var_2 = temp

print(var_1, var_2)

input()

Python Swap Two Variables Using Assign Multiple Variables

var_1 = input('The fisrt variable = ')
var_2 = input('The second variable = ')

var_1, var_2 = var_2, var_1

print(var_1, var_2)

input()

Python Swap Two Numbers Without Using a Temporary Variable

When the type of two variable is number (integer, float…) we can swap them without using a temporary variable.

var_1 = float(input('The fisrt variable = '))
var_2 = float(input('The second variable = '))

var_1 = var_1 + var_2
var_2 = var_1 - var_2
var_1 = var_1 - var_2

print(var_1, var_2)
input()