(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

When a function call itself is knows as recursion. Recursion works like loop but sometimes it makes more sense to use recursion than loop. You can convert any loop to recursion.

Here is how recursion works. A recursive function calls itself. As you you’d imagine such a process would repeat indefinitely if not stopped by some condition. This condition is known as base condition. A base condition is must in every recursive programs otherwise it will continue to execute forever like an infinite loop.

Overview of how recursive function works

- Recursive function is called by some external code.
- If the base condition is met then the program do something meaningful and exits.
- Otherwise, function does some required processing and then call itself to continue recursion.

Here is an example of recursive function used to calculate factorial.

Factorial is denoted by number followed by ( ! ) sign i.e 4!

For e.g

1 | 4! = 4 * 3 * 2 * 1 |

1 | 2! = 2 * 1 |

1 | 0! = 1 |

Here is an example

1 2 3 4 5 6 7 8 9 | def fact(n): if n == 0: return 1 else: return n * fact(n-1) print(fact(0)) print(fact(5)) |

**Expected Output**:

1 2 | 1 120 |

Now try to execute the above function like this

1 | print(fact(2000)) |

You will get

1 | RuntimeError: maximum recursion depth exceeded in comparison |

This happens because python stop calling recursive function after 1000 calls by default. To change this behavior you need to amend the code as follows.

1 2 3 4 5 6 7 8 9 10 11 | import sys sys.setrecursionlimit(3000) def fact(n): if n == 0: return 1 else: return n * fact(n-1) print(fact(2000)) |

#### Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

basemI have found this article is very useful and simple, thanks

palHave a question : When I tried above program with sys.setrecursionlimit(2008), it worked fine for print(fact(2000)), it did not work for any limit between 2001 to 2007.

Can you explain the behavior here ?

lap1have you tried with sys.setrecursionlimit(3000) ?

abubakarthis has been very useful and practical

MikeHi Guru

Can you explain how this happens. With the following piece of code:

def recursion(n):

if n > 0:

print(“recursion”,n)

recursion( n-1 )

print(n)

recursion( 10 )

Which outputs the following:

recursion 10

recursion 9

recursion 8

recursion 7

recursion 6

recursion 5

recursion 4

recursion 3

recursion 2

recursion 1

1

2

3

4

5

6

7

8

9

10

How does it output the the print( n ) statement when it is not within the recursion?

simranRecursive function stop calling after 997 not after 1000