Write a program to swap or exchange two numbers without taking a temporary variable.
In Python, we can swap or exchange two numbers in 3 ways. Check the code 😉
num1 = 10
num2 = 20
print(f"Before swapping: {num1=} and {num2=}")
num1 = num1 + num2 # 10 + 20 = 30
num2 = num1 - num2 # 30 - 20 = 10 <= num2
num1 = num1 - num2 # 30 - 10 = 20 <= num1
print(f"After swapping: {num1=} and {num2=}")
In above code, as you can see first we are storing the sum of num1 and num2 in num1. Next, we are subtracting num2 from num1 and storing the results in num2. Finally, we are performing subtraction (num1 – num2) that we performed in previous step but this time we are storing the results in num1. Thus, both numbers are swapped in num1 and num2.
To Swap Two numbers using XOR operator
num1 = 10
num2 = 20
print(f"Before swapping: {num1=} and {num2=}")
num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2
print(f"After swapping: {num1=} and {num2=}")
In above code, we are using XOR (^) operator to swap two numbers.
To Swap Two numbers: One-liner code 😄
num1 = 10
num2 = 20
print(f"Before swapping: {num1=} and {num2=}")
num1, num2 = num2, num1
print(f"After swapping: {num1=} and {num2=}")
If you have not installed python then download it from here. For more Python related posts, click here.
Comments