源代码:使用临时变量
代码可视化:想确切了解变量交换是如何工作的吗?使用我们全新的代码可视化工具逐行查看。 亲自尝试!
# Python program to swap two variables
x = 5
y = 10
# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
输出
The value of x after swapping: 10 The value of y after swapping: 5
在此程序中,我们使用 temp 变量暂时保存 x 的值。然后,我们将 y 的值赋给 x,再将 temp 的值赋给 y。通过这种方式,值就完成了交换。
源代码:不使用临时变量
在 Python 中,有一种简单的结构可以交换变量。以下代码与上述代码功能相同,但不使用任何临时变量。
x = 5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
如果变量都是数字,我们可以使用算术运算来完成相同的操作。乍一看可能不直观。但如果你仔细思考,会发现这很容易理解。以下是一些示例:
加法和减法
x = x + y
y = x - y
x = x - y
乘法和除法
x = x * y
y = x / y
x = x / y
异或交换
此算法仅适用于整数
x = x ^ y
y = x ^ y
x = x ^ y
另请阅读