Today we will write a program to swap two numbers in Python, we have two ways to do it:
- Swap using temporary variable.
- 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)
before swapping a= 10 b= 20 after swapping a= 20 b= 10
Program to swap two numbers in Python without using temporary variable:
Python provides a way to directly swap two number without temporary variable. It can be done in following way.
a, b = b, a
In this method we can use addition and subtraction operators.
a = a + b b = a - b a = a - b
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.
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.