0

This function prints the nth fibonacci term.

def fib_recur(n, _prev=0, _cur=1, _i=1):
    if n <= 1: print(n)
    elif _i <= n: fib_recur(n, _cur, _cur+_prev, _i+1)
    else: print(_prev)

If altered to just return the nth term:

def fib_recur(n, _prev=0, _cur=1, _i=1):
    if n <= 1: return n    # <- this return does work
    elif _i <= n: fib_recur(n, _cur, _cur+_prev, _i+1)
    else: return _prev     # <- this return does not

The function prints a value but returns None.

Am I missing something or is there something I'm not understanding about the relationship between functions which print vs. return values?

Ed Danileyko
  • 189
  • 2
  • 13
  • 5
    you are missing a `return` on your `elif`. When the function enters the recursion, the "bottommost" layer returns a value, which is then never returned any further up the chain. – Zinki Apr 10 '18 at 06:15
  • you said it - "but `returns none`" – Joseph D. Apr 10 '18 at 06:15

1 Answers1

4

You missing the return in elif condition

def fib_recur(n, _prev=0, _cur=1, _i=1):
    if n <= 1: return n    
    elif _i <= n: return fib_recur(n, _cur, _cur+_prev, _i+1) # missing return
    else: return _prev