Python Program to Swap Two Numbers

python program to swap two numbers

Hey Shouters!! Today we have come up with the python program to swap two numbers.

In this, we will learn all the methods to swap two numbers in python. You will learn to swap two variables by using a temporary variable and, without using a temporary variable.

If you are a beginner and do not know how to write a python program. Please check the Introduction to Python.

What is swapping ?​

Basically, swapping means transferring the value of one variable to another variable. Swapping is a mathematical process and it can be performed in many ways.

Let’s look upon the various methods in python to perform swapping.

Swapping Numbers: Using a temporary variable​-

In this program, we used a third variable named temp, and first we will store one variable in temp and then will do the swapping.

Output
​The value of x after swapping: 10​
The value of y after swapping: 5

Python Program to Swap two numbers- Without Temporary Variable-

In Python, there is a simple construct to swap variables. The following code does the same as above but without the use of any temporary variable.

Output
The value of x after swapping: 10​
The value of y after swapping: 5

1. Using Multiplication and Division for swapping:

This is the further method in swapping two variables without using a temporary variable.

In this method, we will first multiple two variables and will store in one variable and will divide the changed variable with another to swap the variable.

Output​​
The value of x after swapping: 10​
The value of y after swapping: 5

2. Using XOR Bit-wise operator to Swap two varibales:

In this method, we will be using the XOR operator to swap the two variables. Bit-wise operator does the operation on the bits.

Truth Table of XOR- The XOR operator only gives an output when only one input is active/1.

equation
Truth Table of XOR

Output
The value of x after swapping: 10​
The value of y after swapping: 5

Python Program to Swap Two Variables: Using Inbuilt Method-

There is a very simple approach in python to swap two variables and you just need to do the following simple step.

Output
x= 10​
y=  5

Comment down the feedback of the program and if you are on Instagram, do follow us on https://www.instagram.com/shoutcoders/

Recommended Posts-

  1. Introduction to Python and Environment Setup
  2. Python Program to Check a Year is Leap Year or Not
  3. Python Program to Check a Palindrome Number
  4. Word Guessing Game in Python

2 thoughts on “Python Program to Swap Two Numbers

  1. Very happy to see you very well sir, we will benefit a lot from it, you are working very well very very good

Leave a Reply

Your email address will not be published. Required fields are marked *

Close Bitnami banner
Bitnami