Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How can we create recursive functions in Python?

How do I use a recursive python function to find the sum of first 100 and first 500 natural numbers?


1 Answer
Rajendra Dharmkar

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.

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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.