Python Program to swap two numbers using temporary variable

Program

a = int(input("Enter the value of a\n"))
b = int(input("Enter the value of b\n"))
print("Values before swapping:")
print("a: {}\nb: {}\n".format(a,b))
temp = a
a = b
b = temp
print("Values after swapping:")
print("a: {}\nb: {}".format(a,b))

This program swaps two numbers using a temporary variable.

a = int(input("Enter the value of a\n"))
b = int(input("Enter the value of b\n"))
  • The user inputs two numbers (a and b).
  • input() takes the input as a string, and int() converts it to an integer.
print("Values before swapping:")
print("a: {}\nb: {}\n".format(a, b))
  • Displays the original values before swapping.

Swapping Logic using a Temporary Variable:

temp = a  # Store 'a' in a temporary variable
a = b     # Assign 'b' to 'a'
b = temp  # Assign the stored value (original 'a') to 'b'
  • A temporary variable stores the value of a.
  • a is assigned the value of b.
  • b is assigned the stored value of a.
  • This successfully swaps the two numbers.
print("Values after swapping:")
print("a: {}\nb: {}".format(a, b))
  • Prints the swapped values.

Key Takeaways:

Uses a temporary variable to store one value during the swap.
Ensures no data loss while swapping.
Simple and effective method for swapping values in Python.

Output

Enter the value of a
7
Enter the value of b
4
Values before swapping:
a: 7
b: 4
Values after swapping:
a: 4
b: 7