Functions That Call Themselves - Recursive Functions
A recursive function
is a function that calls itself within its own definition and continues to execute repetitively until a certain condition (base case) is met.
Example of Recursive Function
Below is an example of a recursive function that calculates the product of numbers from 1
to the given number
.
Factorial Recursive Function Example
# n! = 1 * 2 * 3 * ... * n def factorial(n): # Base case: when n is 1 if n == 1: # Return 1 and terminate the recursive calls return 1 else: # Multiply n by the value returned from factorial invoked with n - 1 return n * factorial(n - 1) # Function call print(factorial(5)) # 120
When to Use Recursive Functions?
Recursive functions are used to perform repetitive tasks such as calculating the factorial(!)
of numbers, or generating Fibonacci sequences
(a sequence where each number is the sum of the two preceding ones).
They can also be utilized in algorithms
for searching or manipulating data.
Fibonacci Sequence Function Example
def fibonacci(n): # Base case: return n when n is 1 or less if n <= 1: return n # When n is 2 or more else: # Return the sum of the (n-1)th and (n-2)th Fibonacci numbers return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(6)) # 8
Mission
0 / 1
What is the most suitable word to fill in the blank below?
A recursive function is a function that calls within itself.
another function
itself
a termination condition
a loop
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result