Fibonacci Function using Python

Hi. I want to understand step by step how the code below produces the Fibonnaci numbers.
Particularly the for loop.

def fib(n):
    if n < 1:
        return None
    if n < 3:
        return 1

    elem_1 = elem_2 = 1
    the_sum = 0
    for i in range(3, n + 1):
        the_sum = elem_1 + elem_2
        elem_1, elem_2 = elem_2, the_sum
    return the_sum

For example our n is 10.

elem_1 = elem_2 = 1
    the_sum = 0
    for i in range(3, 11):
        the_sum = elem_1 + elem_2
        elem_1, elem_2 = elem_2, the_sum

What values do elem_1 and elem_2 take at a particular range…

Why don’t you try it out?
Just print out the variables within the loop:

print("elem_1 =", elem_1, "; elem_2 =", elem_2)
6 Likes

Print the value of i as well:

print("i=", i, "; elem_1 =", elem_1, "; elem_2 =", elem_2)
1 Like

Just to chip in, you can also simplify debugging by using formatted-strings (f""-literal).
Instead of

print("i=", i, "; elem_1 =", elem_1, "; elem_2 =", elem_2)

you can do

print(f"{i=}; {elem_1=}; {elem_2=}")

which would produce similar output.

1 Like