help reading code very short (fibonacci)

User Generated

xzvnu

Programming

Question Description

I would like someone to explain line by line what this is doing in python:


def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)


Student has agreed that all tutoring, explanations, and answers provided by the tutor will be used to help in the learning process and in accordance with Studypool's honor code & terms of service.

Explanation & Answer

Actually this is returning the nth element in the Fibonacci series using recursion.
Suppose number is 3, then the 3rd element would be 2

LINE 1: defines a function with name fib which is taking a number as parameter n=3
LINE 2-3: if number is zero then return 0. In our case it is not so next statement would be executed
LINE 4-5: else if number is 1 return 1. In our case it is not so next statement
LINE 5-6 else now we calling fib(3-1) + fib(3-2) = 1 + 1 = 2

fib(3-1) execution n=2
LINE 2: would return false goto LINE 4
LINE 4: woudl be false goto LINE 6
LINE 6 would be executed fib(2-1) + fib(2-2) = 1 + 0 = 1
fib(2-1) n=1
LINE 2: return false goto LINE 4
LINE 4: be true do return 1
fib(2-2) n=0
LINE 2: return 0

fib(3-2) n=1
LINE 2: return false goto LINE 4
LINE 4: true return 1

qntenjny (611)
Duke University

Anonymous
Really helped me to better understand my coursework. Super recommended.

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4