-2

How does the fourth line in the code below work?

a, b = 0, 1
while b < 10:
   print b
   a, b = b, a + b

I don't have a problem, I just don't know how it's working.

Saviour
  • 302
  • 2
  • 11
  • It is a case of swap, specifically a tuple swap. It assigns to `a` the value of `b` and to `b` the sum of `a+b`. For further information, check [here](https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python). – Vasilis G. Dec 15 '18 at 16:25
  • 1
    The code specifies that initially `a=0` and `b=1`, in while loop, print the value of `b`, `a=b` (value of `b` is copied into `a`), `b=a+b` (sum of `a` and `b` is copied into `b`) until `b` is lesser than or equal to 9. Output would be: `1 1 2 3 5 8`, forming a fibonacci series – Preetkaran Singh Dec 15 '18 at 16:43
  • @Preetkaran Singh. Fibonacci sequence, not series. – DavidPM Dec 15 '18 at 16:53

1 Answers1

0

If I understand you correctly, you want to explain this line (formatted for readability): a, b = b, a + b.

Essentially you are assigning a tuple to another tuple, and when you do that in python you 'unpack' one tuple into the other. You can read about it here.

In your specific case, firstly the tuple (b, a + b) is evaluated and then it is assigned to the tuple (a, b). For example in the first iteration of the loop a = 0 and b = 1, so (b, a + b) = (1, 1). Therefore the last line will be equivalent to (a, b) = (1, 1).

You can read more in this question.

Saviour
  • 302
  • 2
  • 11