# Why my code does not work?

Here is my code https://code.sololearn.com/cGgzHqn6YYkh/?ref=app I can't understand what's my mistake....

9/16/2021 7:10:06 PM

Kind_Cat19 Answers

New AnswerKind_Cat Maybe this adjustment to your code might help to explain Add up the nums and compare to result # Created by Kind_Cat num = int(input()) print(num,'\n') def fibonacci(n): if n == 0: print(0) return 0 elif n == 1: print(1) return 1 #print (fibonacci(n-1)+fibonacci(n-2)) return fibonacci(n-1)+fibonacci(n-2) print(fibonacci(num))

Try this, it can be helpful def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1)+fibonacci(n-2) num = int(input()) for i in range(num): print(fibonacci(i))

This can not be done with a recursive pure function. recursive: https://code.sololearn.com/czbSIG9KoN7H/?ref=app pure: https://code.sololearn.com/cK02jcB2GUjL/?ref=app edited for clarification : This function has to print a sequence of numbers, not just one number. In a recursive function with two recursion at one call, like this, the function may be executed twice for one input. So there has to be an out-of-function variable that determines if one output has already been printed. for example, f(6) calls f(5) and f(4); And f(5) calls f(4) separately. So if the function prints somthing for f(4), it prints it twice. One solution is that our function have one output and be called multiple times. but it's no longer pure for our purpose.

Agree, it's hard to understand the process of recursion versus iteration ☺️ My suggestion: "1. Create a fibonacci function using a while loop. 2. Create any simple recursive function, for example, print 1,2,3". Post your solutions here Then together we will try to write a recursive function fibonacci 😉

But if you get a straight answer, you will never learn how to create a recursive function correctly.

Kind_Cat Kittu Here're different approaches , try it https://code.sololearn.com/cRa0mh14vkLA/?ref=app I hope it helped ☺️

num = int(input()) def fibonacci(n): if n == 0: print(0) #you should not use print here return 0 elif n == 1: print(1) # no print required return 1 else: # this else must be required , otherwise it will run with every iteration and become endless loop return fibonacci(n-1)+fibonacci(n-2) print(fibonacci(num)) here is edited code https://code.sololearn.com/cD8Nmc10y4mH/?ref=app