Local variable declaration in a PYTHON function

Asked

Viewed 130 times

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 the variables a and b in 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 this, if I declare a, b = b, a+b would not be the same as I declare:

a = b
b = b + a

Thank you.

2 answers

3

The key to understanding this is that everything on the right of the = is executed before by the language, and then she makes the assignments -

then while doing

a, b = b, a + b

(which is the same as :

a, b = (b, a + b)

Python dispenses with 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 tpla is temporarily in memory as a result of the expression - and then these values are distributed and assigned respectively to a and to b.

If you do:

a = b

in a separate line, the value of a has been over-written in making a + b in another line (and the language would not be usable if it did something like this - it would be completely unpredictable).

It is worth remembering that this language of calculating a tuple and associating its values in the same line is used, because without this resource you would need a third variable just to make this exchange - the code in most other languages, which does not have this feature has to be:

c = a
a = b
b = c + b

If you write something like that:

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

the language, in addition to distributing the values of the teporária tuple to a and b, will store the entire tuple in the variable inspecionar. That one print the more will help you understand what is happening.

0

Take a look at Rafael. When you do

a, b = a, a+b

variable A and variable B receive the value at the same time, so when B receives a+b A still has 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?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.