Python Program Code to Swap Two Number

Here you’ll get a python program to swap 2 numbers with and while not victimization temporary variable.

Python Program to Swap 2 Numbers with the use of 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

Python Program to Swap 2 Numbers while not victimization Temporary Variable

Method 1:

Python provides the way to directly swap 2 variety while not temporary variable. It is worn out following method.

a, b = b, a

Method 2:

In this methodology, we will use addition and subtraction operators.

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

Method 3:

We can conjointly swap numbers victimization multiplication and division operator in the following method.

a = a * b
b = a / b
a = a / b

This methodology won’t work once one amongst the amount is zero.

Method 4:

It is another methodology during which we have a tendency to use bitwise xor operator.

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

Comment below if you have got queries or grasp the other thanks to swapping numbers in python.

Leave a Comment

error: Alert: Content is protected!!