Write a Python Program to Swap Two Variables

In Python, swapping the values of two variables is a common task that programmers often encounter.

It involves exchanging the values of two variables so that the value of one variable becomes the value of the other variable and vice versa.

To swap two variables in Python, you can use a simple technique called variable swapping.

Here’s an example Python program that demonstrates how to swap the values of two variables:

# Program to swap two variables

# Take two variables
a = 10
b = 20

# Print the original values
print("Before swapping:")
print("a =", a)
print("b =", b)

# Swap the values
a, b = b, a

# Print the swapped values
print("After swapping:")
print("a =", a)
print("b =", b)

In this program, we first initialize two variables a and b with the values 10 and 20 respectively.

Then, we print the original values of a and b using the print() function.

Next, we swap the values of a and b using the syntax a, b = b, a.

This statement assigns the value of b to a and the value of a to b, effectively swapping their values.

Finally, we print the swapped values of a and b using the print() function again.

When you run this program, you should see the following output:

Before swapping:
a = 10
b = 20
After swapping:
a = 20
b = 10

As you can see, the values of a and b have been successfully swapped using the variable swapping technique.


In conclusion, swapping the values of two variables in Python is a simple task that can be accomplished using the variable swapping technique.

This technique involves assigning one variable’s value to the other variable and vice versa, effectively swapping their values.