12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

44 Chapter 5. Conditionals and recursion__main__countdownn 3countdownn 2countdownn 1countdownn 0As usual, the top of the stack is the frame for __main__. It is empty because we did not create anyvariables in__main__or pass any arguments toit.The four countdown frames have different values for the parameter n. The bottom of the stack,wheren=0,iscalled the base case. It does not make arecursive call, sothere areno moreframes.Draw astack diagram forprint_ncalled withs = 'Hello'andn=2.Writeafunctioncalleddo_nthattakesafunctionobjectandanumber,n,asarguments,and that callsthe given functionntimes.5.10 Infinite recursionIf a recursion never reaches a base case, it goes on making recursive calls forever, and the programnever terminates. This is known as infinite recursion, and it is generally not a good idea. Here is aminimal program withan infinite recursion:def recurse():recurse()In most programming environments, a program with infinite recursion does not really run forever.<strong>Python</strong> reports anerror message when the maximum recursion depth isreached:File "", line 2, in recurseFile "", line 2, in recurseFile "", line 2, in recurse...File "", line 2, in recurseRuntimeError: Maximum recursion depth exceededThis traceback is a littlebigger than the one we saw inthe previous chapter. When the error occurs,there are1000recurseframes on thestack!

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!