Python 交换两个变量程序
在本教程中,我们将学习如何在Python程序中交换两个变量。假设我们有两个变量P和Q;我们必须编写一个Python程序来交换它们的值。我们还将讨论Python中不同的方法来完成这个任务。
方法1:使用原生方法
在这种方法中,原生方法将把变量P的值存储在一个临时变量中,然后将变量P赋值为变量Q的值。然后,它将将临时变量的值赋给变量Q,这将导致交换两个变量的值。
示例:
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
# To swap the value of two variables
# we will user third variable which is a temporary variable
temp_1 = P
P = Q
Q = temp_1
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
输出:
Please enter value for P: 13
Please enter value for Q: 43
The Value of P after swapping: 43
The Value of Q after swapping: 13
方法2:使用逗号操作符
我们可以使用逗号操作符。对于此方法,我们不需要使用第三个变量来交换两个变量的值。
示例:
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
# To Swap the values of two variables
P, Q = Q, P
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
输出:
Please enter value for P: 12
Please enter value for Q: 43
The Value of P after swapping: 43
The Value of Q after swapping: 12
方法3:使用异或方法
我们还可以使用位异或方法来交换两个变量。两个变量P和Q的异或运算将返回一个数字,该数字在P和Q变量的位不同的地方都有1。
例如,4的异或运算结果(二进制为0100)和6的异或运算结果(二进制为0110)是1010。
2的异或运算结果(二进制为0010)和8的异或运算结果(二进制为1000)是1010。
示例:
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
# To Swap the values of two variables using XOR
P = P ^ Q
Q = P ^ Q
P = P ^ Q
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
输出:
Please enter value for P: 12
Please enter value for Q: 10
The Value of P after swapping: 10
The Value of Q after swapping: 12
方法4:使用算术运算符
在这种方法中,我们可以以两种方式交换两个变量的值:
- 使用加法和减法运算符:
示例:
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
# To Swap the values of two variables using Addition and subtraction operator
P = P + Q
Q = P - Q
P = P - Q
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
输出:
Please enter value for P: 15
Please enter value for Q: 43
The Value of P after swapping: 43
The Value of Q after swapping: 15
- 使用乘法和除法运算符
示例:
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
# To Swap the values of two variables using Addition and subtraction operator
P = P * Q
Q = P / Q
P = P / Q
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
输出:
Please enter value for P: 23
Please enter value for Q: 14
The Value of P after swapping: 14.0
The Value of Q after swapping: 23.0
结论
在本教程中,我们讨论了在Python程序中交换两个变量值的各种方法。