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

This function return the sum of the first n figures of the fibonacci sequnce. Can somebody explain me how does it work. I'm confused about calling the function in itself.

Jerven Clark
  • 1,191
  • 2
  • 13
  • 26
  • 1
    [Understanding how recursive functions work](https://stackoverflow.com/questions/25676961/understanding-how-recursive-functions-work) -- it's not about Python, but the concept you're stuck on is not Python-specific in any way. – Charles Duffy Jul 14 '21 at 16:00
  • Does this answer your question? https://stackoverflow.com/a/499245/6781048 – Jerven Clark Jul 14 '21 at 16:01
  • "This function return the sum of the first n figures of the fibonacci sequnce" - no it doesn't, it returns the nth element of the fibonacci sequence. – Robin Zigmond Jul 14 '21 at 16:08

1 Answers1

0

you must learn recursion (recursive functions) then you understand how this function works! Also this is not a good solution, better solution for this program is to use Dynamic Programming for better runtime(too faster when n is high). example to show how this function works:

if n=2 answer --> 1
fib=>0 1 1

fibonacci(n-1) + fibonacci(n-2)=> fibonacci(1) + fibonacci(0) so we have fibonacci(1) which is 1(second if) and we have fibonacci(0) which is 0(first if) and sum of 0and1 is 1 so fib(2) is 1!