Python Program to Swap Two Numbers

Swapping two numbers is a fundamental operation in programming, often used in various algorithms and applications. In this blog, we’ll walk through a Python program that swaps the values of two variables. Let’s dive in!

Understanding Number Swapping

Swapping two numbers means exchanging their values. For example, if we have two variables a and b, after swapping, the value of a will become what was originally in b, and vice versa.

Swapping with a Temporary Variable Python Program

Here’s a step-by-step guide on how to write a Python program to swap two numbers:

def swap_numbers(a, b):
    temp = a
    a = b
    b = temp
    return a, b

# Input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Swapping the numbers
num1, num2 = swap_numbers(num1, num2)

# Output
print("After swapping:")
print(f"First number: {num1}")
print(f"Second number: {num2}")

Swapping Without a Temporary Variable

Now, let’s introduce a method to swap two numbers without using an extra variable:

def swap_without_temp(a, b):
    a = a + b
    b = a - b
    a = a - b
    return a, b

Comparing Both Methods

The first method uses a temporary variable to store one of the values temporarily. The second method uses arithmetic operations to achieve the swapping. Both methods have their advantages and considerations. Swapping without a temporary variable saves memory but can be less intuitive.

How the Program Works

  1. The swap_numbers function takes two numbers as input and uses a temporary variable temp to swap their values.
  2. The user inputs two numbers to be swapped.
  3. The program calls the swap_numbers function and displays the swapped numbers.

Conclusion

Swapping two numbers is a fundamental concept in programming and is often used to rearrange values in variables. This Python program provides a basic example of how to swap two numbers using a temporary variable. You can further expand upon it by exploring other ways to achieve the same result, such as using arithmetic operations or tuple unpacking. Understanding this simple operation is a valuable skill that can be applied in various coding scenarios. Happy coding!