Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Swap two variables using a temporary variable - Python Program

To swap two variables in Python using a temporary variable, a third variable is introduced to temporarily store the value of one of the variables. This allows the values to be exchanged without losing any data.

Here is the process:

  • Store the value of the first variable in the temporary variable.

This preserves the original value of the first variable before it is overwritten.

  • Assign the value of the second variable to the first variable.

The first variable now holds the value that was originally in the second variable.

  • Assign the value of the temporary variable to the second variable.

The second variable now receives the original value of the first variable, which was stored in the temporary variable. 

# Input values in two variables a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) print(f"Before swapping: a = {a}, b = {b}") # Create a temporary variable and store the value of 'a' temp = a # Assign the value of 'b' to 'a' a = b # Assign the value of 'temp' (original 'a') to 'b' b = temp print(f"After swapping: a = {a}, b = {b}")

Output

 
OUTPUT  :
Enter the first number: 10
Enter the second number: 20
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10