Programming
help reading code very short (fibonacci)

Question Description

I’m stuck on a Programming question and need an explanation.

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.

Final 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

dagrawal (611)
Duke University

Anonymous
The tutor was pretty knowledgeable, efficient and polite. Great service!

Anonymous
Heard about Studypool for a while and finally tried it. Glad I did caus this was really helpful.

Anonymous
Just what I needed… fantastic!

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4

Brown University





1271 Tutors

California Institute of Technology




2131 Tutors

Carnegie Mellon University




982 Tutors

Columbia University





1256 Tutors

Dartmouth University





2113 Tutors

Emory University





2279 Tutors

Harvard University





599 Tutors

Massachusetts Institute of Technology



2319 Tutors

New York University





1645 Tutors

Notre Dam University





1911 Tutors

Oklahoma University





2122 Tutors

Pennsylvania State University





932 Tutors

Princeton University





1211 Tutors

Stanford University





983 Tutors

University of California





1282 Tutors

Oxford University





123 Tutors

Yale University





2325 Tutors