0% found this document useful (0 votes)
3 views

Recursion

Uploaded by

ram
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Recursion

Uploaded by

ram
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Recursion

In Python, we know that a function can call other functions. It is even possible for the
function to call itself. These types of construct are termed as recursive functions.

The following image shows the working of a recursive function called recurse.

Example of a recursive function


def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

In the above example, factorial() is a recursive function as it calls itself.

When we call this function with a positive integer, it will recursively call itself by decreasing
the number.

Each function multiplies the number with the factorial of the number below it until it is equal
to one. This recursive call can be explained in the following steps.

factorial(3) # 1st call with 3


3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3 * 2 * 1 # return from 3rd call as number=1
3 * 2 # return from 2nd call
6 # return from 1st call
Our recursion ends when the number reduces to 1. This is called the base condition.

Every recursive function must have a base condition that stops the recursion or else the
function calls itself infinitely.

You might also like