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
- Start
- Take input: Prompt the user to enter the first variable.
- Take input: Prompt the user to enter the second variable.
- Swap the values: Use Python's tuple assignment to swap the values of the two variables.
- Display the result: Print the swapped values.
- 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
- Taking input from the user:
Theinput()
function is used to take input from the user. The values entered are stored in variablesa
andb
. - 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 ofa
andb
are swapped in a single line:a, b = b, a
. This eliminates the need for an extra step with a temporary variable. - Displaying the output:
Theprint()
function is used to display the swapped values. An f-string is used to format the output clearly, showing the new values ofa
andb
.