06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

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.

4.9 Recursion 43<br />

countdown expects the parameter, n, <strong>to</strong> be a positive integer. If n is 0, it outputs<br />

the word, “Blas<strong>to</strong>ff!” Otherwise, it outputs n and then calls a function named<br />

countdown—itself—passing n-1 as an argument.<br />

What happens if we call this function like this:<br />

>>> countdown(3)<br />

The execution of countdown begins <strong>with</strong> n=3, and since n isnot0,i<strong>to</strong>utputsthe<br />

value 3, and then calls itself...<br />

The execution of countdown begins <strong>with</strong> n=2, andsincen is not 0, it<br />

outputs the value 2, and then calls itself...<br />

The execution of countdown begins <strong>with</strong> n=1, andsincen is<br />

not 0, it outputs the value 1, and then calls itself...<br />

The execution of countdown begins <strong>with</strong> n=0, and<br />

since n is 0, it outputs the word, “Blas<strong>to</strong>ff!” and<br />

then returns.<br />

The countdown that got n=1 returns.<br />

The countdown that got n=2 returns.<br />

The countdown that got n=3 returns.<br />

And then you’re back in main (what a trip). So, the <strong>to</strong>tal output looks like<br />

this:<br />

3<br />

2<br />

1<br />

Blas<strong>to</strong>ff!<br />

As a second example, look again at the functions newLine and threeLines:<br />

def newline():<br />

print<br />

def threeLines():<br />

newLine()<br />

newLine()<br />

newLine()<br />

Although these work, they would not be much help if we wanted <strong>to</strong> output 2<br />

newlines, or 106. A better alternative would be this:

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

Saved successfully!

Ooh no, something went wrong!