Write a Program to Swap Two Numbers Without Using Third Variable in Python

Hi, in this blog lets learn how to swap two numbers with out using a third variable in Python Programming Language. The program statement is Write A Python Script To Swap Two Numbers with out using third variable.

Python supports certain simple methods that you can use to swap two numbers. Lets learn them now.


Write a Program to Swap Two Numbers Without Using Third Variable in Python



Python supports a feature when you can swap two numbers with out using the third variable using a single line, lets take two variables and swap it as shown below.

Code :

a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))
 
a, b = b, a
print("Value of First Variable After Swap is : ", a) 
print("Value of Second Variable After Swap is : ", b) 
 

As you can see above python statement a, b = b, a 

This statement is used to swap two variables and exchange the values between them with out using the third variable.


Program to Swap Two Numbers Without Using Third Variable in Python using Arithmetic Operations + & -

a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))

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

print("Value of First Variable After Swap is : ", a) 
print("Value of Second Variable After Swap is : ", b) 

Try using plus, minus and minus with a and b you will get the numbers swapped between two variables with out using third variable.


Program to Swap Two Numbers Without Using Third Variable in Python using Arithmetic Operations * and / 

a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))

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

print("Value of First Variable After Swap is : ", a) 
print("Value of Second Variable After Swap is : ", b)

 

Try get product first and then divide a by b and then again divide a by b to get values of b and a respectively.
 
 

Program to Swap Two Numbers Without Using Third Variable in Python using Arithmetic Operations ^ XOR Operator

 

a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))

a = a ^ b
b = a ^ b
a = a ^ b
print("Value of First Variable After Swap is : ", a)
print("Value of Second Variable After Swap is : ", b)

Use ^ XOR Operator in sequence between a and b to get the values of b and a respectively as shown above.


OUTPUT :

Enter First Number : 4
Enter Second Number : 5
Value of First Variable After Swap is :  5
Value of Second Variable After Swap is :  4

 

Conclusion : Try to run all the program by yourself and comment down below if you have any issue.

 

 

 


Post a Comment

0 Comments