12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

5.9. Stack diagrams for recursive functions 43The execution of countdown begins with n=3, and since n is greater than 0, it outputs the value 3,and then calls itself...The execution of countdown begins with n=2, and since n is greater than 0, it outputsthe value 2, and then callsitself...The execution of countdown begins with n=1, and since n is greater than 0,itoutputs thevalue 1, and then calls itself...The execution of countdown begins with n=0, and since n is notgreater than 0, itoutputs the word, “Blastoff!” and thenreturns.Thecountdownthat gotn=1returns.Thecountdownthat gotn=2returns.Thecountdownthat gotn=3returns.And then you’reback in__main__. So, thetotal output looks likethis:321Blastoff!A function that calls itselfisrecursive; theprocess iscalled recursion.As another example, we can writeafunction that printsastringntimes.def print_n(s, n):if n

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

Saved successfully!

Ooh no, something went wrong!