原文: https://www.programiz.com/python-programming/examples/natural-number-recursion
在此程序中,您将学习使用递归函数查找自然数之和。
要理解此示例,您应该了解以下 Python 编程主题:
在下面的程序中,我们使用了递归函数recur_sum()计算得出给定数字的总和。
源代码
# Python program to find the sum of natural using recursive functiondef recur_sum(n):if n <= 1:return nelse:return n + recur_sum(n-1)# change this value for a different resultnum = 16if num < 0:print("Enter a positive number")else:print("The sum is",recur_sum(num))
输出
The sum is 136
注意:要测试程序的另一个数字,请更改num的值。
