深度阅读

How to swap two numbers in Python

作者
作者
2023年08月22日
更新时间
5.83 分钟
阅读时间
0
阅读量

There are multiple ways to swap two numbers in Python.

  1. Using a temporary variable:
a = 5
b = 7

temp = a
a = b
b = temp

print("a =", a)
print("b =", b)
  1. Using tuple unpacking:
a = 5
b = 7

a, b = b, a

print("a =", a)
print("b =", b)
  1. Using bitwise XOR operator (not recommended for readability reasons):
a = 5
b = 7

a ^= b
b ^= a
a ^= b

print("a =", a)
print("b =", b)

All three methods produce the same output:

a = 7
b = 5

Note that the second method is the most pythonic and readable way to swap two numbers in Python.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。