-2

So the code is

def mystery(n):
    a, b = 0, 1
    while (a < n):
        print(a)
        a, b = b, a + b

The bit I do not understand very well is how a, b = b, a + b works. It seems really difficult to understand for me. I struggle to comprehend how variables work with listing involved. Could someone shed some light on what sequence is being produced and how the numbers tally up.

The sequence is meant to go

0

1

1

2

3

5

8

13

21

34

etc

I would be really greatful, thanks in advance!

Community
  • 1
  • 1
Razor
  • 25
  • 1
  • 4

1 Answers1

2

In a, b = b, a + b, the expressions on the right hand side are evaluated before being assigned to the left hand side. So it is equivalent to:

c = a + b
a = b
b = c

Which is actually swapping in your case so , OP:

a, b = 0,1

will evaluate to b=0 and a=1

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47