问题
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()
The output is dependent on n and returns a valid Fibonacci sequence.
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()
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?
回答1:
Doing:
a, b = b, a+b
is equivalent to:
temp = a
a = b
b += temp
It lets you simultaneously do two calculations without the need of an intermediate/temporary variable.
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.
Examples
>>> 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
回答2:
In
a, b = b, a+b
the right-hand expressions are evaluated first, and their results are assigned to a
and b
. This is similar to the following:
_new_a = b
_new_b = a+b
a = _new_a
b = _new_b
On the other hand, in
a = b
b = a+b
you are modifying a
before adding it to b
. This is equivalent to
a, b = b, b+b
which explains where the powers of two are coming from.
来源:https://stackoverflow.com/questions/23085008/python-usage-of-variables-and-their-difference-a-b-0-1-vs-a-0-b