Python Program to Swap Two Variables

This article is created to cover a program in Python that swaps two variables. The program to swap two variables, is created with and without using the third variable.

Python Swap Two Variables using Third Variable

The question is, write a Python program to swap two variables. Answer to this question, is the program given below:

print("Enter any Value for First Variable: ", end="")
variableOne = input()
print("Enter any Value for Second Variable: ", end="")
variableTwo = input()

print("\nBefore Swap:")
print("Value of \"variableOne\" =", variableOne)
print("Value of \"variableTwo\" =", variableTwo)

x = variableOne
variableOne = variableTwo
variableTwo = x

print("\nAfter Swap:")
print("Value of \"variableOne\" =", variableOne)
print("Value of \"variableTwo\" =", variableTwo)

The snapshot given below shows the sample run of above Python program, with user input 5 and 10 as two values for first and second variable namely variableOne and variableTwo

python program swap two variables

Python Swap Two Variables without using Third Variable

To swap two variables in Python, but without using the third variable. Then replace the following statements, from previous program:

x = variableOne
variableOne = variableTwo
variableTwo = x

with a single statement given below:

variableOne, variableTwo = variableTwo, variableOne

That is, the value of variableTwo gets initialized to variableOne, whereas the value of variableOne gets initialized to variableTwo.

Python Online Test


« Previous Program Next Program »



Like/Share Us on Facebook 😋