Python Program to SWAP two numbers


Way 1 – Using temp Variable

In [1]:
x = int(input("Please enter x : "))
y = int(input("Please enter y : "))

temp = x
x = y
y = temp

print("-------------------")
print("New value of x =", x)
print("New value of y =", y)
Please enter x : 5
Please enter y : 8
-------------------
New value of x = 8
New value of y = 5

In this program, we use temporary variable temp to swap two numbers.

Way 2 – Without using temp Variable

In [1]:
x = int(input("Please enter x : "))
y = int(input("Please enter y : "))

x, y = y, x

print("-------------------")
print("New value of x =", x)
print("New value of y =", y)
Please enter x : 5
Please enter y : 9
-------------------
New value of x = 9
New value of y = 5

This program does not use any temporary variable to swap two numbers. Here, we use multiple variable assignment for that.