# 5 ways to swap two numbers in Python
# 1. Using a Temporary Variable:
a = 5
b = 10
temp = a
a = b
b = temp
print("After swapping: a =", a, ", b =", b)
#clcoding.com
# 2. Without Using a Temporary Variable :
a = 5
b = 10
a = a + b
b = a - b
a = a - b
print("After swapping: a =", a, ", b =", b)
#clcoding.com
# 3. Using Tuple Unpacking:
a = 5
b = 10
a, b = b, a
print("After swapping: a =", a, ", b =", b)
#clcoding.com
# 4. Using XOR bitwise operation:
a = 5
b = 10
a = a ^ b
b = a ^ b
a = a ^ b
print("After swapping: a =", a, ", b =", b)
#clcoding.com
# 5. Using Arithmetic Operators in a Single Line:
a = 5
b = 10
a, b = b, a + b - a
print("After swapping: a =", a, ", b =", b)
#clcoding.com
0 Comments:
Post a Comment