Two problems
There are two problems with your code:
- There is an infinite loop, which generates the
RecursionError exception
- It is impossible to retrieve all terms of the sequence (you said you want to print all the sequence, not only the last term)
The infinite loop
Try the code below. I just added n==1 as another stop condition.
def fib(n):
n = int(n)
if n == 0 or n == 1: # Changed here
return 1
return fib(n - 1) + fib(n - 2)
num = input("Give me a number: ")
print(fib(num))
The case f(1)=1 is required by definition (see here).
Or just debugging your code, you will realize that the loop will never end for fib(1) because it returns:
f(1-1) + f(1-2) >>> f(0) + f(-1) >>> 1 + infinite loop.
Printing all terms
You could try to use lists in your recursive code, which is tricky to do or perhaps change to a version with loops.
With loops:
# A version using a while loop
# This code returns the list of terms
def fib(n):
n=int(n)
terms = []
i=0
while i<=n:
if i==0 or i==1:
terms.append(1)
else:
terms.append(terms[-2]+terms[-1])
i+=1
return terms
Recursive:
Working on it
Try all these examples here.
fib(-1)return? If you're thinking "fib never gets called with a negative argument", consider whatreturn fib(n - 1) + fib(n - 2)does whennequals 1.fib(n - 2)will give you an n of-1whennis 1.1, I think you'll see the problem. Isfib(1 - 2)ever going to terminate?RecursionErrorfor large values ofneven if you fix the current issue. This is not a good way to compute arbitrary Fibonacci numbers.