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=', ')
    my_print(n-1)   
my_print(5)
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
print(sys.getrecursionlimit())
sys.setrecursionlimit(2000)
print(sys.getrecursionlimit())
Output
1000
2000

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=', ')
    my_print(n-1)
my_print(5)
The best example to use recursive function is to create Fibonacci series and to generate factorial of a number.
All Sample codes Armstrong Number

Podcast on Python Basics


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







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 Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer