Python: Usage of Variables and their difference ("a, b = 0, 1" VS "a = 0", "b = 1")

fibonacci, python, variables

Solution

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

Problem

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?

Original source