Local variables declaration in a PYTHON function [duplicate]

2
def fib(n):
    a, b = 0, 1    
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

result- > 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

But if I declare variables a and b on different lines, it brings me another result:

def fib(n):
    a = 0
    b = 1
    while a < n:
        print(a, end=' ')
        a = b      'declarar a = b, não seria o mesmo que acima'
        b = a + b
     print()

result - > 0 1 2 4 8 16 32 64 128 256 512 1024

The question is, if I declare a, b = b, a+b would not be the same as I declare:

a = b
b = b + a

Thank you.

    
asked by anonymous 08.08.2018 / 16:06

2 answers

3

The key to understanding this is that everything to the right of = is executed first by the language, and then it does the assignments -

So while doing

a, b = b, a + b

(which is the same as:

a, b = (b, a + b)

Python dispenses parentheses if there is no ambiguity)

What happens is that an object of type tuple is created with the current value of b, and the value of a + b as its two elements. This tuple is temporarily in memory as a result of the expression - and then these values are distributed and assigned respectively to and to b.

If you do:

a = b

On a separate line, the value of a has already been overwritten by doing a + b on another line (and the language would not be usable if you did something like this - it would be completely unpredictable).

Remember that this language to calculate a tuple and associate its values in a same line is used, because without this feature you would need a third variable just to make this exchange - the code in most other languages, which does not have this feature must be:

c = a
a = b
b = c + b

If you write something like this:

a, b = inspecionar = b, a+b
print(a, b, inspecionar)

The language, in addition to distributing the values of the tuple teporaria to a and b , will save the entire tuple in the inspecionar variable. This% w / w% more will help you understand what is happening.

    
08.08.2018 / 16:41
0

Look at Rafael well. When you do

a, b = a, a+b

variable A and variable B get the value at the same time, so when B receives a + b A is still with the value of the previous loop the previous value.

When you do

a = b
b = a+b

At the moment B receives the value, the variable A has already changed the value, so the difference, understood?

    
08.08.2018 / 16:29