Write a Python program that swaps the values of two variables. For example, if a = 5 and b = 10, after swapping, a should be 10 and b should be 5. This simple task is useful in various algorithms and programming scenarios.
There are multiple ways to swap two variables, let's discuss each of them one by one:
Approach 1: Using a Temporary Variable.
The first approach uses a temporary variable to store one of the values, allowing us to perform the swap.
Step-by-step Algorithm:
- Store the value of an in a temporary variable (temp).
- Assign the value of b to a.
- Assign the value of temp to b.
Python Code Implementation.
# Python program to swap two variables using temp variable # Before swapping a = 5 b = 10 print(f"Before swapping: a = {a}, b = {b}") # Swap logic temp = a a = b b = temp # After swapping print(f"After swapping: a = {a}, b = {b}")
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
Approach 2: Without Using a Temporary Variable.
The second approach swaps values without using a temporary variable, using arithmetic operations.
Step-by-step Algorithm:
- Add the values of a and b and store the result in a.
- Subtract the original value of a (now stored in b) from a.
- Subtract the original value of b from a to get the original value of a in b.
Python Code Implementation.
# Python program to swap two variables a = 5 b = 10 print(f"Before swapping: a = {a}, b = {b}") # Without using a temporary variable a = a + b b = a - b a = a - b # After swapping print(f"After swapping: a = {a}, b = {b}")
Output:
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
Approach 3: Using Tuple Unpacking.
The third approach leverages the Pythonic way of swapping values using tuple unpacking.
Step-by-step Algorithm:
- Create a tuple with the values of a and b.
- Unpack the tuple into variables a and b.
Python Code Implementation.
# Python program to swap two variables using tuple a = 5 b = 10 print(f"Before swapping: a = {a}, b = {b}") # Using tuple unpacking a, b = b, a # After swapping print(f"After swapping: a = {a}, b = {b}")
Output:
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
These are a few ways to swap two variables you can choose any method based on your requirements and convenience.
Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.
No comments
Post a Comment