×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

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

  1. Storing the value of one variable (x) in a different variable (namely temporary - temp).
  2. Then changing the value of x by copying the value of y.
  3. 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 »

Advertisement
Advertisement

Related Programs

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.