Python Program to Swap Two Variables

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:

  1. Using a temporary third variable.
  2. 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)