Recursion
Recursion
Recursion is a programming technique in which a function calls itself to solve a problem. The function continues to call itself until a base condition is met, at which point the function stops calling itself and returns a value.
In Python, recursion is implemented using the same function calling syntax as normal functions. However, it is important to ensure that there is a base condition that eventually stops the recursion, otherwise, the program will enter an infinite loop.
Here’s an example of how to calculate the nth number in the Fibonacci sequence using recursion in Python:
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
# Example usage
n = 6
fib_n = fibonacci(n)
print("The", n, "th Fibonacci number is", fib_n)
In this example, the fibonacci() function recursively calls itself to calculate the nth number in the sequence. The function first checks if n is 0 or 1, as these are the base cases. If n is not 0 or 1, the function recursively calls itself with the arguments (n-1) and (n-2) to calculate the sum of the two preceding numbers in the sequence. The recursion continues until the base cases are reached and the function returns a value.