python 中的变量赋值查询

Variable assignment query in python

我正在 python 中编写斐波那契代码。以下解决方案是我的。

而下面的另一个解决方案来自 python.org。

谁能告诉我为什么即使分配变量的逻辑相同,它也会产生不同的答案?

我在你的解决方案中看到额外的选项卡,而且你的程序逻辑是错误的。据我所知,通过写作 fib(5) 你想要系列中的第 5 个斐波那契数(即 5)而不是小于 5(即 3)的数字。

a=b
b=a+b

a,b = b,a+b

不相等。

看下面的代码。

def fibonacci(num):
    a,b=0,1;
    counter = 2;
    while(a<=):
        a,b = b,a+b
        counter += 1
    return b

print fibonacci(5)

它在第二个示例中起作用的原因是因为 a=b 在两个都完成之前不会计算。所以当它到达 b=a+b 部分时, a 仍然是它之前的值。在你的第一个例子中,你在使用它之前覆盖 a 。在 python 中,当您以这种方式声明变量时,您实际上是在将它们用作元组。这意味着在整行完成之前,它们将保留其原始值。一旦元组被解包,它们就会被覆盖。

这两个程序不等价。等号 (=) 的右侧一起计算。 正在做:

a=b
b=a+b

不同于:

a,b = b,a+b

这实际上等同于:

c = a
a = b
b = b + c

你的例子实际上在 Python documentation:

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

线条

a = b # Assigns the value of 'b' to 'a'
b = a + b # Adds the new value of 'a' to 'b'

然而,

a, b = b, a+bb 的值赋给 a。将 a 现有 值添加到 b