Python:变量的用法及其差异("a,b = 0,1" VS"a = 0","b = 1")

编程入门 行业动态 更新时间:2024-10-25 02:19:34
本文介绍了Python:变量的用法及其差异("a,b = 0,1" VS"a = 0","b = 1")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在查看Python手册,并找到了斐波那契数生成器的以下代码段:

I was looking at the Python Manual and found this snippet for a Fibonacci-Number generator:

def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print()

输出取决于n并返回有效的斐波那契数列.

The output is dependent on n and returns a valid Fibonacci sequence.

如果您将其重塑为像这样分别使用变量"a"和"b":

If you remodel this to use the variables "a" and "b" seperately like so:

def fib(n): # write Fibonacci series up to n a = 0 b = 1 while b < n: print(b, end=' ') a = b b = a+b print()

然后它将打印一个以2的幂递增的数字序列(例如1、2、4、8、16等).

then it will print a number sequence that increments by the power of 2 (e.g. 1, 2, 4, 8, 16 and so on).

所以我想知道为什么会这样吗?两次使用变量之间的实际区别是什么?

So I was wondering why that happens? What is the actual difference between the two uses of variables?

推荐答案

操作:

a,b = b,a + b

等效于:

temp = a a = b b += temp

它使您可以同时进行两个计算,而无需中间/临时变量.

It lets you simultaneously do two calculations without the need of an intermediate/temporary variable.

区别在于,在第二段代码中,当您执行第二行 b = a + b 时,您已经在上一行中修改了 a 与第一段代码不同.

The difference is that in your second piece of code, when you do the second line b = a+b, you have already modifed a in the previous line which is not the same as the first piece of code.

>>> a = 2 >>> b = 3 >>> a,b 2 3 >>> a,b = b,a >>> a,b 3 2

另一方面,如果您使用问题中显示的第二种方法:

On the other hand, if you use the second approach shown in your question:

>>> a = 2 >>> b = 3 >>> a,b 2 3 >>> a = b >>> b = a >>> a,b 3 3

更多推荐

Python:变量的用法及其差异("a,b = 0,1" VS"a = 0","b = 1")

本文发布于:2023-11-30 00:37:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648140.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   差异   Python   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!