1

my code is:

nums = [1,1]
def fib(n):
    nums.append(nums[-1]+nums[-2])
    if len(nums)-1 != n:
        fib(n)
    elif len(nums)-1 == n: 
        return nums

print(fib(5))
print(nums)

I see that the function returns None though nums is not None.Thanks in advance.

anurag
  • 85
  • 1
  • 1
  • 5

1 Answers1

0

Change it please to

def fib(n):
    nums.append(nums[-1] + nums[-2])
    if len(nums) - 1 != n:
        return fib(n)
    elif len(nums) - 1 == n:
        return nums
t4kq
  • 754
  • 1
  • 5
  • 11
  • why should a return statement be there when we are just calling the function again and not returning any value to calling statement? – anurag Jul 10 '21 at 12:10
  • Cause recursive function always need to return statement. As you see on the simplest example of recursion - factorial - you will see - return statement need to collect data after recursive finished. – t4kq Jul 10 '21 at 12:13