Python Program to Swap Two Variables Using X-OR Operation

Python program to swap two variables using x-or operation can be implemented by using a bit-wise operator like x-or. Swapping of two numbers means the exchanging of values between them.






1. Python Program & output to swap two Numbers using X-Or Operation

Code has been copied
# *************************************************
#           alphabetacoder.com
# Python program to swap two numbers without third
# variable but using bit-wise operator X-OR
# *************************************************

# take input of two numbers
num1, num2 = map(int, input("Enter two numbers = ").split())

print("Before swapping: number1 =", num1, " and number2 =", num2)

# do swapping using X-OR(^)
num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2

print("After swapping: number1 =", int(num1), " and number2 =", int(num2))

Output


Enter two numbers = 5 2

Before swapping: number1 = 5 and number2 = 2

After swapping: number1 = 2 and number2 = 5