Skip to content
Home » Swap two numbers in Python using XOR operator

Swap two numbers in Python using XOR operator

Learn about Swap two numbers in Python using XOR operator in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

Swap two numbers in Python using XOR operator

# Program to swap two numbers using XOR operator

# input from user
a = int(input('value of a: '))
b = int(input('value of b: '))

print('Values Before Swapping')
print('a = ',a, 'and b = ',b)

# swapping of the numbers using XOR
a = a ^ b
b = a ^ b
a = a ^ b

# print swapped values
print('Values After Swapping')
print('a = ',a, 'and b = ',b)

Output:

value of a: 3
value of b: 4
Values Before Swapping
a =  3 and b =  4
Values After Swapping
a =  4 and b =  3

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Code : Swap two numbers in Python using * and / operator