Python递归函数在完成后返回none [英] Python recursive function returning none after completion

查看:101
本文介绍了Python递归函数在完成后返回none的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码应该从 n 倒计时到 1.代码完成但最后返回 None.关于为什么会发生这种情况以及如何解决它的任何建议?提前致谢!

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()

推荐答案

print(countdown(n)) 打印 countdown(n) 返回的值.如果 n >0,返回值为None,因为如果没有执行return语句,Python函数默认返回None.

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.

由于您在 countdown 中打印值,因此修复代码的最简单方法是删除 main() 中的 print 调用:

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()

删除了 else-clause,因为文档字符串表示最后打印的值是 1,而不是 0.

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

这篇关于Python递归函数在完成后返回none的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆