Python Program to Swap Two Variables

Introduction

Swapping the values of two variables is a common task in programming. This tutorial will guide you through creating a Python program that swaps the values of two variables without using a temporary variable.

Problem Statement

Create a Python program that:

  • Takes two variables and swaps their values.

Example:

  • Input: x = 5, y = 10
  • Output: After swapping: x = 10, y = 5

Solution Steps

  1. Initialize Two Variables: Start by assigning values to two variables.
  2. Swap the Variables: Use Python’s multiple assignment feature 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
# Author: https://www.javaguides.net/

# Step 1: Initialize two variables
x = 5
y = 10

# Step 2: Swap the variables
x, y = y, x

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

Explanation

Step 1: Initialize Two Variables

  • Assign values to two variables, x and y. In this example, x = 5 and y = 10.

Step 2: Swap the Variables

  • Python allows you to swap the values of two variables in a single line using the syntax x, y = y, x. This is a concise and efficient way to swap values without needing a temporary variable.

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 include the variable values directly within the string.

Output Example

Example:

After swapping: x = 10, y = 5

Conclusion

This Python program demonstrates how to swap the values of two variables using Python’s multiple assignment feature. This approach is simple and efficient, making it a common practice in Python programming. This example is particularly useful for beginners to understand variable manipulation in Python.

Leave a Comment

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

Scroll to Top