Last answered:

03 Dec 2021

Posted on:

03 Dec 2021

0

Resolved: Fibonacci Series Step Through

I am having trouble grasping how python steps through the Fibonacci series. The code in the lectures defines the function as:

def fib(n):
    a = 0
    b = 1
    for i in range(n):
        a,b = b,b+a
        return a

However, if I try to step through the fist 3 values in the series, I derive an incorrect value, which cannot be the case.

a = 1
b = 1+0 = 1

a = 2
b = 1 + 1 = 2

a = 4
b = 2 + 2 = 4

What is python actually doing to obtain the correct value?

Thank you!

1 answers ( 1 marked as helpful)
Instructor
Posted on:

03 Dec 2021

1

Hey Patrick,

Thank you for your question!

Let's perform the first couple of iterations. We start with a = 0 and b = 1. Then, we enter the for-loop.

For i = 0:
a, b = 1, 1 + 0
=> a, b = 1, 1

For i = 1:
a, b = 1, 1 + 1 = 2
=> a, b = 1, 2

For i = 2:
a, b = 2, 2 + 1 = 3
=> a, b = 2, 3

and so on..

Hope this helps!

Kind regards,
365 Hristina

Submit an answer