# Help understanding syntax (beginner q, probably dumb)

I’m on my own, trying to learn Python from a book. I write a simple code snippet to sum Fibonacci numbers up to 100 as follows:

a, b, sum_of_fibs = 0, 1, 0

while b < 100:
sum_of_fibs += b
c = b # temp store b
b = a + b # get next fib no.
a = c # new a = previous b

print(“sum of Fibonacci numbers < 100 =”,sum_of_fibs)

Clear to me and it generates the correct sum, 232.

However, I found that someone has written the essential algorithm as follows (same 1st & last lines):

while b < 100:
sum_of_fibs += b
a, b=b, a+b

This works too, but I do not understand that 3rd line. (“a” standing alone? b = b? seems very strange)

Can someone kindly explain this syntax and what is going on here?

Thanks very much.

You have been fooled by the poor choice of spacing.

The code that confuses you is written:

``````a, b=b, a+b
``````

which makes it look like `a` on its own, then the weird assignment
`b=b`, then the sum `a+b` which isn’t saved anywhere. But that’s just
an illusion caused by misleading spacing.

It might be easier to read if we improve the spacing, or add
parentheses:

``````a,b = b,a+b

# Better still:
(a, b) = (b, a+b)
``````

This is called “sequence unpacking assignment”, and it is (roughly)
equivalent to:

``````a = b
b = a+b
``````

I say roughly because the unpacking doesn’t get literally unrolled into
two separate lines like that. It happens all at nce, so you can use it
to swap two variables:

``````a,b = b, a
``````

is like:

``````temp = a
a = b
b = temp
del temp
``````

except there is no actual “temp” variable used.

Wow. The clouds part, light shines in.

And a neat one-line SWAP too.

Thanks much. I will have more questions – hope I haven’t used up my quota…