Use of the comma in Python

Asked

Viewed 692 times

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)
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

1


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

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

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

tSomador = somador
somador = inicio
inicio += tSomador

I put in the Github for future reference.

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

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

And finally, this code has several other errors, everything I said is worth if the errors are fixed.

  • An example that illustrates this is that it is possible to change the value of variables by doing a, b = b, a.

  • Because this result of 3 lines is the code of any swap, did magic :)

Browser other questions tagged

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