Home »
Python »
Python Programs
Python program for swapping the value of two integers
Learn how to swap the value of two integers using third variable using Python program.
By Anuj Singh Last updated : January 04, 2024
Problem statement
Given two numbers, write a Python program to swap them.
Algorithm to swap two numbers
- Storing the value of one variable (x) in a different variable (namely temporary - temp).
- Then changing the value of x by copying the value of y.
- Then changing the value of y by copying the value of temp.
Three simple steps, three simple variables and its all done.
Python program for swapping the value of two integers
# Code toto to swap two numbers
# Input the numbers
x = int(input("ENTER THE VALUE OF X: "))
y = int(input("ENTER THE VALUE OF Y: "))
# Printing numbers before swapping
print("Before swapping:")
print("X :", x, " Y :", y)
# Swapping the numbers
temp = x
x = y
y = temp
# Printing numbers after swapping
print("After swapping:")
print("X :", x, " Y :", y)
Output
The output of the above example is:
RUN 1:
ENTER THE VALUE OF X: 100
ENTER THE VALUE OF Y: 200
Before swapping:
X : 100 Y : 200
After swapping:
X : 200 Y : 100
RUN 2:
ENTER THE VALUE OF X: 108
ENTER THE VALUE OF Y: 1008
Before swapping:
X : 108 Y : 1008
After swapping:
X : 1008 Y : 108
To understand the above program, you should have the basic knowledge of the following Python topics:
Python Basic Programs »