Python Program to Swap Two Variables Without a Temporary Variable

Introduction

Swapping the values of two variables without using a temporary variable is a common programming challenge. This tutorial will guide you through creating a Python program that accomplishes this using simple arithmetic operations.

Problem Statement

Create a Python program that:

  • Takes two variables and swaps their values without using a temporary variable.

Example:

  • Input: x = 15, y = 25
  • Output: After swapping: x = 25, y = 15

Solution Steps

  1. Initialize Two Variables: Start by assigning values to two variables.
  2. Swap the Variables Using Arithmetic Operations: Use addition and subtraction to swap the values.
  3. Display the Result: Use the print() function to display the values of the variables after swapping.

Python Program

# Python Program to Swap Two Variables Without a Temporary Variable
# Author: https://www.javaguides.net/

# Step 1: Initialize two variables
x = 15
y = 25

# Step 2: Swap the variables using arithmetic operations
x = x + y  # x now becomes 40
y = x - y  # y now becomes 15 (original value of x)
x = x - y  # x now becomes 25 (original value of y)

# Step 3: Display the result
print(f"After swapping: x = {x}, y = {y}")

Explanation

Step 1: Initialize Two Variables

  • Assign initial values to two variables, x and y. In this example, x = 15 and y = 25.

Step 2: Swap the Variables Using Arithmetic Operations

  • The values of x and y are swapped using arithmetic operations:
    1. First, add the two variables and store the result in x. Now, x holds the sum of both original values.
    2. Subtract the new value of x by y to assign the original value of x to y.
    3. Finally, subtract the new value of y from x to assign the original value of y to x.

Step 3: Display the Result

  • The print() function is used to display the values of x and y after swapping. The f-string format is used to directly include the variable values within the string.

Output Example

Example:

After swapping: x = 25, y = 15

Conclusion

This Python program demonstrates how to swap the values of two variables without using a temporary variable by utilizing arithmetic operations. This method is efficient and avoids the need for additional memory allocation, making it a valuable technique in resource-constrained environments.

Leave a Comment

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

Scroll to Top