Python Program To Swap Two Numbers

Write Python code to swap two numbers

# WAP to swap two numbers

a = 45
b = 54
print("\nBefore swapping a =", a, "and b =", b)
# method - 1(IMP)
a, b = b, a
print("After swapping a =", a, "and b =", b)

a = 44
b = 55
print("\nBefore swapping a =", a, "and b =", b)
temp = a
a = b
b = temp
print("After swapping a =", a, "and b =", b)

a = 45
b = 55
print("\nBefore swapping a =", a, "and b =", b)
a = a + b
b = a - b
a = a - b
print("After swapping a =", a, "and b =", b)

Output:

Before swapping a = 45 and b = 54
After swapping a = 54 and b = 45

Before swapping a = 44 and b = 55
After swapping a = 55 and b = 44

Before swapping a = 45 and b = 54
After swapping a = 54 and b = 45

<< Previous | Next >>


Leave a Reply

Your email address will not be published.