Python Program to Swap Two Numbers

Here you will get python program to swap two numbers with and without using temporary variable.

Python Program to Swap Two Numbers Using Temporary Variable

Output

before swapping
a= 10 b= 20

after swapping
a= 20 b= 10

Python Program to Swap Two Numbers 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.

Method 2:

In this method we can use addition and subtraction operators.

Method 3:

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

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.

Comment below if you have queries or know any other way to swap numbers in python.

Leave a Comment

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