How can you swap the values of two variables in Python?

There are multiple ways to swap the values of two variables, here is one of the methods:

a = 10
b = 20

a, b = b, a

print("a =", a)  # 输出结果应为20
print("b =", b)  # 输出结果应为10

In this example, we achieved the exchange of values between variables a and b by unpacking a tuple to assign the values simultaneously.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds