[Tutor] Understanding error in recursive function

Alan Gauld alan.gauld at btinternet.com
Fri Apr 8 19:38:20 EDT 2016


On 08/04/16 21:48, Tom Maher wrote:

> As a test I am trying to write a function that returns the sum of values
> attached to one key in a dictionary. I am wondering why the code that I
> wrote is returning:
> "maximum recursion depth exceeded "

Python has a limit to how many times you can recursively call a
function. (Last time I looked it was about 1000) You have hit it.

The problem is you have broken one of the primary rules of recursion,
you are not checking for the terminating condition before recursively
calling the function. As soon as you enter the function you call it
again - forever... or until Python hits its limits.

> def howMany(aDict):
>       count = 0
>       for value in howMany(aDict):

Effectively your code never gets further than this.

You need to think about what will stop the recursion and how
to test for that before calling the next level.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list