Use of the comma in Python [duplicate]

0

I'm having a problem understanding the difference between code 1 and code 2 (Fibonacci sequence). Apparently it looked the same, but the results they both print are distinct.

Code 1

qtd_elementos = int(input())
inicio = 1
somador = 0
lista_elementos = []

while (len(acumulador)) < qtd_elementos:
    somador, inicio = inicio, inicio + somador
    lista_elementos.append(somador)
print(acumulador)

Code 2

qtd_elementos = int(input())
inicio = 1
somador = 0
lista_elementos = []

while (len(acumulador)) < qtd_elementos:
    somador = inicio
    inicio += somador
    lista_elementos.append(somador)
print(acumulador)
    
asked by anonymous 13.06.2018 / 08:49

1 answer

1

The comma separates two expressions in the language. In other contexts it may be a slightly different interpretation, but always close to it.

In this case on the left side of the assignment operator you are putting two variables somador and inicio and on the right side you are putting the expressions inicio and inicio + somador . In just one line you can do two different assignments. So it's the same as having made these assignments in separate lines, as was done in code 2. Porting is just a syntax simplifier.

However, there is an important difference in the first somador that receives the value of inicio that has not yet been changed and only after inicio receives its new value which is inicio + somador and this somador used now does not yet received the value of inicio . It's all like it's one thing, it's like this:

tSomador = somador
somador = inicio
inicio += tSomador

The second code does not have the storage for this intermediate variable.

This is a tuple operation, although some may say that not since the tuple syntax is a little different.

And to finish, this code has several other errors, everything I said is worth it if the bugs are fixed.

    
13.06.2018 / 12:19