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
  • 119
  • 1
  • 13
  • Possible duplicate of [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – OneCricketeer Apr 10 '18 at 06:15
  • 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

3

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