Lecture
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
Lessons in this chapter · Recursive and Lambda Functions
- 1. Functions That Call Themselves - Recursive Functions
- 2. Comparing Loop and Recursive Functions
- 3. Enhancing Recursive Function Efficiency with Memoization
- 4. Handling UnboundLocalError in Recursion
- 5. Multiple-choice quiz
- 6. Using Functions and Tuples Together
- 7. Functions within Functions - Callback Functions
- 8. Processing Sequences with filter() and map() Functions
- 9. Multiple-choice quiz
- 10. Creating Concise Anonymous Functions with Lambda
- 11. Calculating Fibonacci Sequence Using Lambda Functions
- 12. Coding Quiz - Extract Elements from List
- 13. Multiple-choice quiz
- 14. Fill-in-the-blank quiz
Quiz
0 / 1
Which of the following 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
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help