我的代码应该从n倒数到1.代码完成但最后返回None。有关为什么会发生这种情况以及如何解决问题的任何建议?提前致谢!
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()
答案 0 :(得分:1)
print(countdown(n))
打印countdown(n)
返回的值。如果n > 0
,返回的值为None,因为如果没有执行return
语句,Python函数默认返回None。
由于您要在countdown
内打印值,因此修复代码的最简单方法是删除print
中的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
,因为docstring表示最后打印的值是1,而不是0。
答案 1 :(得分:1)
删除print(countdown(n))
并将其替换为countdown(n)
。
当n大于0时,倒计时函数会返回任何内容,因此print语句正在打印None
。您也可以在countdown(n)
中删除您的其他声明 - 因为您从不关心倒计时的返回值,所以它没有用处。
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)
# No need to return a value from here ever - unused in the recursion and
# you don't mention wanting to have zero printed.
#else:
# return 0
def main():
# Main function to test countdown
n = eval(input("Enter n: "))
# Don't print the result of countdown - just call it
#print(countdown(n))
countdown(n)
if __name__ == '__main__':
main()
答案 2 :(得分:0)
您希望将递归调用返回到countdown
的下一次调用:
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)
return 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()
这样,当达到基本情况时,返回值0应该向上传播回堆栈并返回。
不幸的是,因为你的基本情况返回0,这导致打印0.但是,如果你想要返回一些东西(想想你是否真的需要在这种情况下)这将是你如何做它
如果您不需要返回任何内容,则无需打印结果。进一步修改
print(countdown(n))
到
countdown(n)