Python Program to Swap Two Values

Write a Python Program to Swap two values

Python examples interviewgigSwapping Two Values:

Swapping two values means exchanging their positions. In mathematics and programming, swapping is often used to interchange the values of two variables. It’s a common operation when you want to reorder or exchange data without losing any information.

Python Program to Swap Two Values:

Here’s a Python program that swaps the values of two variables:

# Taking input from the user
a = int(input("Enter the first value (a): "))
b = int(input("Enter the second value (b): "))
temp = a  # Swapping the values
a = b
b = temp  # Displaying the swapped values
print("After swapping:")
print("Value of a:", a)
print("Value of b:", b)

Explanation:

  • The program starts by taking two integer inputs from the user using the input() function and converting them into integers using the int() function. These inputs are stored in the variables a and b.
  • To swap the values of a and b, a temporary variable temp is introduced to hold the value of a temporarily.
  • The value of a is assigned the value of b, effectively swapping their values.
  • The value of b is then assigned the value stored in temp, which is the original value of a.
  • Finally, the program displays the swapped values of a and b using the print() function.

Output:

Enter the first value (a): 5
Enter the second value (b): 10
After swapping:
Value of a: 10
Value of b: 5

In this example, if the user enters 5 for a and 10 for b, the program swaps their values and displays the result: “Value of a: 10” and “Value of b: 5”.

Scroll to Top