Recursive functions in Python
In this lesson, you will learn about recursive functions in python and how to use them in programs.
Recursive functions in Python
We can define a function to call the other functions when necessary in python. When a defined function calls itself directly or indirectly, it is called a recursive function. Using the recursion function you can loop through data to reach a result.
While writing a recursive it is very easy for a user to slip into writing a function that never terminates, or one that uses excess amounts of memory or processor power. But is a very efficient way of complex programming.
Sample program using a recursive function in python
Input:
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1364′,’_blank’)”]
def simple_recursion(x): if(x>0): return_value = x+simple_recursion(x-1) print(return_value) else: return_value = 0 return return_value print("\n\nRecursion function") simple_recursion(3)
Output:
Recursion function 1 3 6
Another common example of using recursive function is the Fibonacci series
Input
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1365′,’_blank’)”]
def fibonacci_series(n): if n <= 1: return n else: return(fibonacci_series(n-1) + fibonacci_series(n-2)) n_terms = 7 if n_terms <= 0: print("Fibonacci series cannot be printed") else: print("Fibonacci series using recursive function:") for i in range(n_terms): print(fibonacci_series(i))
Output:
Fibonacci series using recursive function: 0 1 1 2 3 5 8