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.

32 Functions<br />

This function takes two arguments, concatenates them, and then prints the result<br />

twice. We can call the function <strong>with</strong> two strings:<br />

>>> chant1 = "Pie Jesu domine, "<br />

>>> chant2 = "Dona eis requiem."<br />

>>> catTwice(chant1, chant2)<br />

Pie Jesu domine, Dona eis requiem. Pie Jesu domine, Dona eis requiem.<br />

When catTwice terminates, the variable cat is destroyed. If we try <strong>to</strong> print it,<br />

we get an error:<br />

>>> print cat<br />

NameError: cat<br />

Parameters are also local. For example, outside the function printTwice, there<br />

is no such thing as bruce. If you try <strong>to</strong> use it, <strong>Python</strong> will complain.<br />

3.11 Stack diagrams<br />

To keep track of which variables can be used where, it is sometimes useful <strong>to</strong> draw<br />

a stack diagram. <strong>Like</strong> state diagrams, stack diagrams show the value of each<br />

variable, but they also show the function <strong>to</strong> which each variable belongs.<br />

Each function is represented by a frame. A frame is a box <strong>with</strong> the name of a<br />

function beside it and the parameters and variables of the function inside it. The<br />

stack diagram for the previous example looks like this:<br />

__main__<br />

chant1<br />

chant2<br />

"Pie Jesu domine,"<br />

"Dona eis requiem."<br />

catTwice<br />

part1<br />

part2<br />

cat<br />

"Pie Jesu domine,"<br />

"Dona eis requiem."<br />

"Pie Jesu domine, Dona eis requiem."<br />

printTwice<br />

bruce<br />

"Pie Jesu domine, Dona eis requiem."

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

Saved successfully!

Ooh no, something went wrong!