Computer >> Computer tutorials >  >> Programming >> Python

How can we create recursive functions in Python?


Recursion is a programming method, in which a function calls itself one or more times in its body. Usually, it is returning the return value of this function call. If a function definition follows recursion, we call this function a recursive function.

A recursive function has to terminate to be used in a program. It terminates, if with every recursive call the solution of the problem is becomes smaller and moves towards a base case, where the problem can be solved without further recursion. A recursion can lead to an infinite loop, if the base case is not met in the calls.

Example

The following code returns the sum of first n natural numbers using a recursive python function.

def sum_n(n):
    if n== 0:
        return 0
    else:
        return n + sum_n(n-1)

This prints the sum of first 100 natural numbers and first 500 natural numbers

print(sum_n(100))
print(sum_n(500))

 Output

C:/Users/TutorialsPoint1/~.py
5050
125250