python 交换两个数字_交换两个数字的Python程序
python 交换两个数字
Here you will get python program to swap two numbers with and without using temporary variable.
在这里,您将获得python程序,可以在不使用临时变量的情况下交换两个数字。
Python程序使用临时变量交换两个数字 (Python Program to Swap Two Numbers Using Temporary Variable)
a = 10
b = 20
print("before swapping\na=", a, " b=", b)
temp = a
a = b
b = temp
print("\nafter swapping\na=", a, " b=", b)
Output
输出量
before swapping a= 10 b= 20
交换前 a = 10 b = 20
after swapping a= 20 b= 10
交换后 a = 20 b = 10
Python程序无需交换临时变量即可交换两个数字 (Python Program to Swap Two Numbers Without Using Temporary Variable)
方法1: (**Method 1:**)
Python provides a way to directly swap two number without temporary variable. It can be done in following way.
Python提供了一种无需临时变量即可直接交换两个数字的方法。 可以通过以下方式完成。
a, b = b, a
方法2: (**Method 2:**)
In this method we can use addition and subtraction operators.
在这种方法中,我们可以使用加减运算符。
a = a + b
b = a - b
a = a - b
方法3: (Method 3:)
We can also swap numbers using multiplication and division operator in following way.
我们还可以按以下方式使用乘法和除法运算符交换数字。
a = a * b
b = a / b
a = a / b
This method will not work when one of the number is 0.
当数字之一为0时,此方法将不起作用。
方法4: (Method 4:)
It is another method in which we use bitwise xor operator.
这是我们使用按位xor运算符的另一种方法。
a = a ^ b
b = a ^ b
a = a ^ b
Comment below if you have queries or know any other way to swap numbers in python.
如果您有疑问或知道以其他方式在python中交换数字,请在下面评论。
翻译自: https://www.thecrazyprogrammer.com/2017/04/python-program-swap-two-numbers.html
python 交换两个数字
还没有评论,来说两句吧...