Python 程序:交换两个变量
在此示例中,您将学习使用临时变量(而不使用临时变量)交换两个变量。
要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:
源代码:使用临时变量
# 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
XOR 交换
此算法仅适用于整数
x = x ^ y y = x ^ y x = x ^ y