Python Program to Swap Two Numbers without using Third Variable

Swapping two numbers is a common task in programming. In Python, it can be achieved using a temporary variable. However, an alternative method allows swapping two numbers without using an extra variable. In this program, we will explore this technique and implement it in Python.

Problem statement

Write a Python program that takes two numbers as input and swaps their values without using a third variable.

Python Program to Swap Two Numbers without using Third Variable

# Function to swap two numbers without using a third variable
def swap_numbers(a, b):
    print("Before swapping:")
    print("a =", a)
    print("b =", b)
    
    a = a + b
    b = a - b
    a = a - b
    
    print("After swapping:")
    print("a =", a)
    print("b =", b)

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

swap_numbers(num1, num2)

Input\output

Python Program to Swap Two Numbers without using Third Variable

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...