Python 程序交换两个变量

2024 年 9 月 5 日 | 阅读 3 分钟

在本教程中,我们将学习如何在 Python 程序中交换两个变量。假设我们有两个变量 P 和 Q; 我们必须编写一个 Python 程序来交换它们的值。我们还将讨论 Python 中用于完成此任务的不同方法。

方法 1:使用朴素方法

在这种方法中,朴素方法会将 P 变量的值存储在一个临时变量中,然后将 Q 变量的值赋给变量 P。 然后,它会将临时变量的值分配给 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:使用逗号运算符

我们可以使用逗号运算符。对于这种方法,我们不需要使用第三个变量来交换两个变量的值。

示例

输出

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:使用 XOR 方法

我们还可以使用按位 XOR 方法来交换两个变量。两个变量 P 和 Q 的 XOR 将返回一个数字,该数字的所有位均为 1,只要 P 和 Q 变量的位不同。

例如,4(二进制 0100)和 6(二进制 0110)的 XOR 是 1010。

2(二进制 0010)和 8(二进制 1000)的 XOR 是 1010。

示例

输出

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:使用算术运算符

在这种方法中,我们可以通过两种方式交换两个变量的值

  • 使用加法和减法运算符

示例

输出

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
  • 使用乘法和除法运算符

示例

输出

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 程序中交换两个变量值的各种方法。