If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Certainly! Here's an example of a recursive function in Python that calculates the factorial of a non-negative integer:
pythonCopy code
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Test the function
result = factorial(5)
print(result) # Output: 120
In this example, the factorial
function uses recursion to calculate the factorial of a non-negative integer n
. It follows the two essential steps of recursion: a base case to terminate the recursion and a recursive case to break down the problem into smaller subproblems.
When n
is equal to 0, the function reaches the base case and returns 1. Otherwise, it multiplies n
with the factorial of n-1
by making a recursive call to factorial(n - 1)
. The recursive calls continue until the base case is reached, at which point the recursion starts to unwind, returning the factorial value.
In the example, factorial(5)
returns the factorial of 5, which is 120.
Recursion is a powerful technique, but it's important to ensure that the base case is properly defined and that the recursion terminates. Without a proper base case, the function could go into an infinite recursion loop.
It's worth noting that for large values of n
, recursive solutions may hit recursion depth limits. In such cases, iterative or alternative approaches may be considered.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform