0

I'm looking at this fibonacci sequence program from python

#!/usr/bin/python3

# simple fibonacci series
# the sum of two elements defines the next set
a, b = 0, 1
while b < 50:
    print(b)
    a, b = b, a + b
print("Done")

The resulting output looks like this: 1, 1, 2 ,3 ,5 ,8 ,13 ,21, 34, Done

I'm slightly confused by the syntax of a, b = b, a + b

What's an equivalent version of this that is more expanded out?

EDIT ANSWER

Okay after reading up on things, below is one equivalent way, with a c temporary placeholder to grab original a

#!/usr/bin/python3

# simple fibonacci series
# the sum of two elements defines the next set
a = 0
b = 1
c = 0
while b < 50:
    print(b)
    c = a
    a = b
    b = a + c
print("Done")

More ways here: Is there a standardized method to swap two variables in Python? , including tuples, xor, and temp variable (like here)

Vincent Tang
  • 3,758
  • 6
  • 45
  • 63
  • 1
    https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python – G_M Jun 14 '17 at 19:16
  • it's a double assignment. `a` takes the value of `b`, while `b` takes the value of the original `a+b` – Jean-François Fabre Jun 14 '17 at 19:16
  • 1
    I found this site to be invaluable in understanding some of what Python does: http://www.pythontutor.com/visualize.html#code=a,%20b%20%3D%200,%201%0Awhile%20b%20%3C%2050%3A%0A%20%20%20%20print%28b%29%0A%20%20%20%20a,%20b%20%3D%20b,%20a%20%2B%20b%0Aprint%28%22Done%22%29&cumulative=false&curInstr=30&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=2&rawInputLstJSON=%5B%5D&textReferences=false – thumbtackthief Jun 19 '17 at 16:00
  • thumbtack this looks very helpful! has every debug line of code :). Any other tools you recommend ;p – Vincent Tang Jun 20 '17 at 20:46

1 Answers1

1

a, b = b, a + b

is the equivalent of

a = b; b = a + b except this would use the new value of a when assigning to b, not the original as intended.

thumbtackthief
  • 6,093
  • 10
  • 41
  • 87