Program to swap two numbers in Python

Today we will write a program to swap two numbers in Python, we have two ways to do it:

  1. Swap using temporary variable.
  2. Swap without using temporary variable.

 

Program to swap two numbers in Python using temporary variable:

a = 10

b = 20

 

print("before swapping\na=", a, " b=", b)

 

temp = a

a = b

b = temp

 

print("\nafter swapping\na=", a, " b=", b)

OUTPUT:

before swapping
a= 10 b= 20

after swapping
a= 20 b= 10

 

Program to swap two numbers in Python without using temporary variable:

Method 1:

Python provides a way to directly swap two number without temporary variable. It can be done in following way.

a, b = b, a

 

Method 2:

In this method we can use addition and subtraction operators.

a = a + b
b = a - b
a = a - b

Method 3:

We can also swap numbers using multiplication and division operator in following way.

a = a * b
b = a / b
a = a / b
This method will not work when one of the number is 0.

 

Method 4:

It is another method in which we use bitwise xor operator.

a = a ^ b
b = a ^ b
a = a ^ b

 

 

Comment below for any help.

Leave a Comment