Here is an example of a Python program for swapping two variables. In Python, swapping values can be done in multiple ways. In this tutorial, we’ll cover:
- Using a temporary third variable.
- Without using a third variable.
Example: Python program to swap two variables using a temporary variable.
#Accept Input
a = int(input("Enter First Number"))
b = int(input("Enter Second Number"))
print("Before swapping:")
print("A =", a)
print("B =", b)
temp = a
a = b
b = temp
print("\nAfter swapping:")
print("A =", a)
print("B =", b)
Example: Swapping Code Without Using a Temporary Variable.
Python makes swapping easy with tuple. Python allows multiple assignment in one line using tuples.
#Accept Input
a = int(input("Enter First Number"))
b = int(input("Enter Second Number"))
print("Before swapping:")
print("A =", a)
print("B =", b)
a, b = b, a
print("\nAfter swapping:")
print("A =", a)
print("B =", b)