Python Recursion Function
Recursion is a powerful technique in programming where a function calls itself during its execution. A recursive function allows you to break down a complex problem into simpler sub-problems by calling itself repeatedly.
Basic syntax of a recursive function
1def recursive_function(parameters): 2 if base_case_condition(parameters): 3 return base_case_value 4 recursive_function(modified_parameters)
The recursive function should have two cases, a base case where it returns a value without calling itself, and a recursive case where it calls itself with modified parameters until it reaches the base case.
Example: Factorial of a number using recursion
1def factorial(n): 2 if n == 1: 3 return 1 4 else: 5 return n * factorial(n-1) 6 7print(factorial(5))
Output:
1120
In the above example, we have a function factorial
that calculates the factorial of a given number n
recursively. If n
is equal to 1, it returns 1, otherwise it calls itself with the modified parameter n-1
until it reaches the base case where n
is equal to 1.
Example: Fibonacci sequence using recursion
1def fibonacci(n): 2 if n == 1 or n == 2: 3 return 1 4 else: 5 return fibonacci(n-1) + fibonacci(n-2) 6 7for i in range(1, 11): 8 print(fibonacci(i), end=" ")
Output:
11 1 2 3 5 8 13 21 34 55
In the above example, we have a function fibonacci
that calculates the nth number in the Fibonacci sequence recursively. If n
is equal to 1 or 2, it returns 1, otherwise it calls itself with the modified parameters n-1
and n-2
until it reaches the base case where n
is equal to 1 or 2.
Recursion is a very powerful technique, but it should be used with caution as it can easily lead to infinite loops if not implemented properly.