Swap Two Numbers in Python: 2 Easy Methods

There are multiple ways to swap the positions of two numbers, here is one method:

a = 5
b = 10

# 方法一:使用临时变量
temp = a
a = b
b = temp

print("交换后的a:", a)
print("交换后的b:", b)

# 方法二:不使用临时变量
a, b = b, a

print("再次交换后的a:", a)
print("再次交换后的b:", b)

In the code above, we initially used a temporary variable to swap the positions of two numbers, and then we swapped the positions of the two numbers again without using a temporary variable.

bannerAds