[Tutor] RuntimeError: maximum recursion depth exceeded

Alan Gauld alan.gauld at btinternet.com
Thu Apr 19 23:25:01 CEST 2012

On 19/04/12 20:51, James Stauble wrote:
> I have seen in a few places where this means my program is essentially
> in an endless loop,

Yes same here. Its not necessarily an endless loop it may just be 
processing more items that Pythons call stack can hamndle, but in this 
case it is endless.

> #This function gets the tip which will be added to the meal
> def getTip(mealPrice):
>      tipPercent = getTip(mealPrice)

Here it is, you call the same function recursively with no break 
condition. But you don't want a loop here anyway you just want
the tip which is a one-off calculation.

In general its best to restrict the use of recursion in Python to 
traversing recursive data structures (like trees and linked lists),
and even then only where you know the depth will be well within
Python's recursion limit (usually set to 1000 I think). And always, 
always, always, write recursive functions to have a termination 
condition, usually at the top of the function. Then ensure the
recursive calls move the function towards that condition if at all 
possible. If you can't write it that way you should recode it as
a regular loop.


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list