Python program to swap two variables

In this example, you will learn about swapping variables in Python.

Imagine a software engineer needs to swap the values of two variables in order to update the state of a program. They can use this program to do so efficiently and without the risk of introducing bugs.

a = input("Enter the value of variable a: ")
b = input("Enter the value of variable b: ")

print(f"Before swapping, a = {a} and b = {b}.")

# Swap the values of a and b
temp = a
a = b
b = temp

print(f"After swapping, a = {a} and b = {b}.")

The program prompts the user to input the values of two variables a and b. It then outputs the values of a and b before swapping, using an f-string.

The program then swaps the values of a and b by temporarily storing the value of a in a variable called temp, assigning the value of b to a, and then assigning the value of temp to b.

Finally, the program outputs the values of a and b after swapping, using another f-string.

Enter the value of variable a: 3
Enter the value of variable b: 7
Before swapping, a = 3 and b = 7.
After swapping, a = 7 and b = 3.

In this example, the program correctly swaps the values of a and b, so that a becomes 7 and b becomes 3. This program can be easily adapted for use in a variety of software engineering applications where it is necessary to swap the values of two variables.

Leave a Comment