python 交换两个数字_交换两个数字的Python程序

悠悠 2022-12-07 13:58 290阅读 0赞

f1422893d77d710e98a000d2b10077be.png

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)

  1. a = 10
  2. b = 20
  3. print("before swapping\na=", a, " b=", b)
  4. temp = a
  5. a = b
  6. b = temp
  7. 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提供了一种无需临时变量即可直接交换两个数字的方法。 可以通过以下方式完成。

  1. a, b = b, a

方法2: (**Method 2:**)

In this method we can use addition and subtraction operators.

在这种方法中,我们可以使用加减运算符。

  1. a = a + b
  2. b = a - b
  3. a = a - b

方法3: (Method 3:)

We can also swap numbers using multiplication and division operator in following way.

我们还可以按以下方式使用乘法和除法运算符交换数字。

  1. a = a * b
  2. b = a / b
  3. 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运算符的另一种方法。

  1. a = a ^ b
  2. b = a ^ b
  3. 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 交换两个数字

发表评论

表情:
评论列表 (有 0 条评论,290人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python交换变量

    之前有段时间想用python写个交换两个变量的值的函数,我们知道在C++中是传入两个变量的指针或者引用,但是python中并没有指针或者引用的概念,而且资源回收全部由pytho

    相关 数字交换三种方法

          今天偶然看到了有一篇文章讲解了交换两个数字的方法,感觉很新颖,拿来说一下。      这种问题通常都是我们在学习java基础的时候可能就会做一些小练习,相信大多数