Python Program to swap two variables

Write a Python program to swap the values of two variables without using a temporary variable.

Input-Output Examples

plaintext
Example 1:
Input:
Enter first number: 5
Enter second number: 10
Output:
After swapping:
First number: 10
Second number: 5

Example 2:
Input:
Enter first number: 20
Enter second number: 40
Output:
After swapping:
First number: 40
Second number: 20

Algorithm

  1. Start
  2. Take input: Prompt the user to enter the first variable.
  3. Take input: Prompt the user to enter the second variable.
  4. Swap the values: Use Python's tuple assignment to swap the values of the two variables.
  5. Display the result: Print the swapped values.
  6. End

Python Program to swap two numbers

python
# Python program to swap two variables without using a temporary variable

# Take input from the user for the first variable
a = input("Enter the first number: ")

# Take input from the user for the second variable
b = input("Enter the second number: ")

# Swap the values using tuple unpacking
a, b = b, a

# Display the result after swapping
print(f"After swapping: \nFirst number: {a} \nSecond number: {b}")

Code Explanation

  1. Taking input from the user:
    The input() function is used to take input from the user. The values entered are stored in variables a and b.
  2. Swapping the values:
    Python provides a simple and efficient way to swap two variables without using a temporary variable. This is done using tuple unpacking, where the values of a and b are swapped in a single line: a, b = b, a. This eliminates the need for an extra step with a temporary variable.
  3. Displaying the output:
    The print() function is used to display the swapped values. An f-string is used to format the output clearly, showing the new values of a and b.
tools

Python

Related Articles