Python Program to Swap Two Numbers

This article is created to cover a program in Python that swaps two numbers, entered by user at run-time of the program.

Python Swap Two Numbers using Third Variable

The question is, write a Python program to swap two numbers. Both the number must be received by user. The program given below is its answer:

print("Enter the First Number: ", end="")
a = int(input())
print("Enter the Second Number: ", end="")
b = int(input())

print("\nBefore Swap")
print("a =", a)
print("b =", b)

x = a
a = b
b = x

print("\nAfter Swap")
print("a =", a)
print("b =", b)

The snapshot given below shows the sample run of above Python program, with user input 200 as first, whereas 500 as second number:

python program swap two numbers

Python Swap Two Numbers without using Third Variable

The question is, write a Python program to swap two numbers without using third variable. To create a program for this question, only replace the following statements, from above program:

x = a
a = b
b = x

with these 3 statements:

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

Rest of all the codes remains same as of previous program.

Python Swap Two Numbers using Bitwise Operator

This is the last program of this article, that does the same job as of previous two programs, but using the Bitwise Operator. The bitwise operator used in this program is, Bitwise XOR (^). I've not written the complete code, the main three statements, I've written over here. Rest of all the codes, are again same.

a = a ^ b
b = a ^ b
a = a ^ b

Same Program in Other Languages

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!