Liu Junhan
Liu Junhan

Reputation: 15

Why a, b = b, a + b is not equal to a = b, b = a + b when I running a fib() in python?

I am new in python programming, and I am trying writing fib based on the generator. And I tried this:

def fib(n):
  a = 0
  b = 1
  for _ in range(n):
     yield a
     print(a)
     a, b = b, a + b
     print((a,b))

and This one:

def fib(n):
  a = 0
  b = 1
  for _ in range(n):
    yield a
    a = b 
    b = a + b
print(list(fib(a)))

the results are different, why would that happen?

Upvotes: 0

Views: 173

Answers (2)

ramazan polat
ramazan polat

Reputation: 7900

Python doesn't break this

a, b = b, a + b 

into this:

a = b
b = a + b

Instead, Python compiler evaluates right hand of an expression first by converting this:

a = 0
b = 1
a, b = b, a + b

into this:

a = 0
b = 1
a, b = 1, 1

then assigns it in proper order. So a and b becomes 1.

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54223

Step through and find out!

a = 0
b = 1

# loop starts:                         # loop starts
yield a    # yields 0,   a=0, b=1      yield a        # yields 0,   a=0, b=1
a = b      #             a=1, b=1      a, b = b, b+a  #             a=1, b=1
b = a + b  #             a=1, b=2
# loop
yield a    # yields 1,   a=1, b=2      yield a        # yields 1,   a=1, b=1
a = b      #             a=2, b=2      a, b = b, b+a  #             a=1, b=2
b = a + b  #             a=2, b=4
# loop
yield a    # yields 2    a=2, b=4      yield a        # yields 1,   a=1, b=2
a = b      #             a=4, b=4      a, b = b, b+a  #             a=2, b=3
b = a + b  #             a=4, b=8
# etc...

Upvotes: 0

Related Questions