Python Program is Designed to Swap Two Numbers

Python Program is Designed to Swap Two Numbers
Reading Time: 5 minutes

Introduction:

This Python program is designed to swap two numbers entered by the user without using a third variable. Swapping is a common programming operation that involves interchanging the values of two variables. In this case, the program will utilize arithmetic operations to achieve the swapping without the need for an additional variable. It showcases a method of achieving variable value interchange while emphasizing the mathematical concept of addition and subtraction.

Algorithm:

  1. Accept input from the user for num1 and num2, which are the two numbers to be swapped.
  2. Add the values of num1 and num2, storing the result in num1. (At this point, num1 contains the sum of the original num1 and num2.)
  3. Subtract the value of num2 from the updated num1, storing the result in num2. (Now, num2 holds the original value of num1.)
  4. Subtract the original value of num2 from the updated num1, storing the result in num1. (Finally, num1 contains the original value of num2.)

As a result of these operations, the values of num1 and num2 are effectively swapped without using an additional third variable.

Python Code :

    
     # Get input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Swap the numbers without using a third variable
num1 = num1 + num2
num2 = num1 - num2
num1 = num1 - num2
# Print the swapped numbers
print("After swapping:")
print("First number:", num1)
print("Second number:", num2)

    
   

Input :

    
     Enter the first number: 5
Enter the second number: 81
    
   

Output :

    
     After swapping:
First number: 81.0
Second number: 5.0
    
   

Explanation:

  1. The program starts by prompting the user to enter two numbers, num1 and num2.
  2. The values of num1 and num2 are added together and stored in the variable num1. This step effectively overwrites the original value of num1.
  3. The value of num2 is calculated by subtracting the original value of num2 (which is now stored in num1) from the updated value of num1. This step assigns the original value of num1 to num2, thus swapping their values.
  4. The final step involves subtracting the original value of num2 from the updated value of num1. This assigns the original value of num2 to num1, completing the swapping process.

After the swapping is complete, the program prints the swapped values of num1 and num2 to the user.

It’s important to note that while this method is a clever way to swap values without using a third variable, it might not be the most efficient or reliable solution for all scenarios, especially when dealing with very large or very small numbers due to potential precision issues.