Home / Programs / Python program to swap two variables -By using XOR method
Programming Example

Python program to swap two variables -By using XOR method

👁 247 Views
💻 Practical Program
📘 Step by Step Learning
Python program to swap two variables -By using XOR method

Information & Algorithm

We can also use the bitwise XOR method for swapping two variables. The XOR of two variables, P and Q, will return the number which has all the bits as 1 whenever the bits of the P and Q variables differ.

Such as XOR of 4 (in binary 0100) and 6 (in binary 0110) is 1010.

XOR of 2 (in binary 0010) and 8 (in binary 1000) is 1010.

Program Code

P = int( input("Please enter value for P: "))  
Q = int( input("Please enter value for Q: "))  
   
# To Swap the values of two variables using XOR  
P = P ^ Q  
Q = P ^ Q  
P = P ^ Q  
   
print ("The Value of P after swapping: ", P)  
print ("The Value of Q after swapping: ", Q)  

Output

Please enter value for P:  12
Please enter value for Q:  10
The Value of P after swapping: 10
The Value of Q after swapping: 12

Explanation

No

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.