[Tutor] Infinite Recursion

Steven D'Aprano steve at pearwood.info
Sun Oct 12 11:03:52 CEST 2014


On Sun, Oct 12, 2014 at 09:41:40AM +0200, William Becerra wrote:
> Hey, I'm new to programming.
> Using python 2.7.8 and running windows8 OS
> I'm reading 'How to think like a computer scientist, learning with Python'
> I'm in chapter 4 sub-chapter 4.11 Infinite recursion
> 
> According to the book if I write
> def recurse():
>       recurse()
> I should get the following error
> File"<stdin>", line2, in recurse
> ( 98 repetitions omittted)
> File "<stdin>", line 2, in recurse
> RuntimeError: Maximum recursion depth exceeded.
> 
> I don't get that error, instead the Python shell prints out two blank lines.

*Two* blank lines? I can't reproduce that. Are you perhaps using 
IPython? Or IDLE? 

Either way, I expect that you have forgotten the brackets (parentheses) 
on the *inner* call to `recurse`. If I type this instead:

def recurse():
    recurse


recurse()  # Call the function.


notice that there are no parens on the inner call, so what happens is 
that when I enter "recurse()", Python executes the function. Inside the 
body of the function, Python grabs a reference to the "recurse" 
function, but *does not call it*. Because it's not called, the recursion 
stops immediately.

It may help you understand the difference to play around with these 
functions. Copy and paste them into the shell:


def recurse1():  # Actually a lie, not really recursing at all.
    print "Look up the name 'recurse1' and see if it exists:"
    recurse1
    print "Done!"


def recurse2():
    print "Look up the name 'recurse2' and call it:"
    recurse2()
    print "Done!"



-- 
Steven


More information about the Tutor mailing list