Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

recursion - Python recursive function returning none after completion

My code is supposed to countdown from n to 1. The code completes but returns None at the end. Any suggestions as to why this is happening and how to fix it? Thanks in advance!

def countdown(n):

    '''prints values from n to 1, one per line
    pre: n is an integer > 0
    post: prints values from n to 1, one per line'''

    # Base case is if n is <= 0
    if n > 0:
        print(n)
        countdown(n-1)
    else:
        return 0

def main():

    # Main function to test countdown
    n = eval(input("Enter n: "))
    print(countdown(n))

if __name__ == '__main__':
    main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

print(countdown(n)) prints the value returned by countdown(n). If n > 0, the returned value is None, since Python functions return None by default if there is no return statement executed.

Since you are printing values inside countdown, the easiest way to fix the code is to simply remove the print call in main():

def countdown(n):

    '''prints values from n to 1, one per line
    pre: n is an integer > 0
    post: prints values from n to 1, one per line'''

    # Base case is if n is <= 0
    if n > 0:
        print(n)
        countdown(n-1)

def main():

    # Main function to test countdown
    n = eval(input("Enter n: "))
    countdown(n)

if __name__ == '__main__':
    main()

Edit: Removed the else-clause since the docstring says the last value printed is 1, not 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...