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.
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.
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 = a + b
b = a - b
a = a - b
Program to Swap Two Numbers Without Using Third Variable in Python using Arithmetic Operations * and /
a = a * b
b = a / b
a = a / b
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.
0 Comments