简体   繁体   中英

Function prints a value but returns none

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?

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     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM