[Tutor] very elementary help ... for total analphabet
alan.gauld@bt.com
alan.gauld@bt.com
Mon, 14 Jan 2002 10:55:45 -0000
> The following code is taken from "Learning to think like a Computer
> Scientist with Python":
>
> class Node:
...
> def printBackward(list):
> if list == None: return
> head = list
> tail = list.next
> printBackward(tail) ## CALLS ITSELF - THIS IS "RECURSION"
> print head,
The problem you have is that the function calls itself.
This is known technically as recursion.
You might find an alternative explanation of the concept
helps, in which case take a look at my web page on it at:
http://www.freenetpages.co.uk/hp/alan.gauld/
Go down to Advanced topics|Recursion in the table of contents.
> (And this already puzzles me, I would have thought return to cause the
> whole printBackward() to terminate - therefore no output at all).
It does cause the whole *current version* of printBackwards
to terminate so the program then executes the next line
which is print head. Its a bit like one of those Russian
dolls - each call nested within another. Once you get to
the bottom level - the empty list, you start putting them
back together again.
Don't worry if this takes a while to sink in, you won't
be the first to struggle with the concept. But once you do
get it, its extremely powerful.
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld