Recursion in Python

Recursion is the way of calling the same function from within the function or the function calling itself. This is required when we have more repetitive process to execute.
def my_print(n):
    print(n,end=', ')
Above code will generate error saying, RecursionError: maximum recursion depth exceeded in comparison as this will continue the recursion steps infinitely.

In our real life situation we can imagine by placing one object between two parallel mirrors. This will generate infinite number of images.

Recursion in python to call the same function again with getrecursionlimit() & setrecursionlimit()

Getting and setting recursion limits

To stop the recursion to happen infinite times, Python provides one setting to allow maximum recursion steps to execute. This setting value we can read by using getrecursionlimit(). By default this value is set at 1000. We can change this limit by using setrecursionlimit(). Here is the code.
import sys

Using stop value.

In our code we will use one condition to create a situation to come out of the recursion and return to the calling process. Here in this code as long as the value of n is equal to or more than 0 , the recursive call to the same function is executed. So this code will print from 5 till 0.
def my_print(n):
  if (n >=0):
    print(n,end=', ')
The best example to use recursive function is to create Fibonacci series and to generate factorial of a number.
All Sample codes Armstrong Number
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer