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
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
3.12 Functions <strong>with</strong> results 33<br />
The order of the stack shows the flow of execution. printTwice was called by<br />
catTwice, andcatTwice was called by main , which is a special name for the<br />
<strong>to</strong>pmost function. When you create a variable outside of any function, it belongs<br />
<strong>to</strong> main .<br />
Each parameter refers <strong>to</strong> the same value as its corresponding argument. So, part1<br />
has the same value as chant1, part2 has the same value as chant2, andbruce<br />
has the same value as cat.<br />
If an error occurs during a function call, <strong>Python</strong> prints the name of the function,<br />
and the name of the function that called it, and the name of the function that<br />
called that, all the way back <strong>to</strong> main .<br />
For example, if we try <strong>to</strong> access cat from <strong>with</strong>in printTwice, we get a NameError:<br />
Traceback (innermost last):<br />
File "test.py", line 13, in __main__<br />
catTwice(chant1, chant2)<br />
File "test.py", line 5, in catTwice<br />
printTwice(cat)<br />
File "test.py", line 9, in printTwice<br />
print cat<br />
NameError: cat<br />
This list of functions is called a traceback. It tells you what program file the<br />
error occurred in, and what line, and what functions were executing at the time.<br />
It also shows the line of code that caused the error.<br />
Notice the similarity between the traceback and the stack diagram.<br />
coincidence.<br />
It’s not a<br />
3.12 Functions <strong>with</strong> results<br />
You might have noticed by now that some of the functions we are using, such<br />
as the math functions, yield results. Other functions, like newLine, perform an<br />
action but don’t return a value. That raises some questions:<br />
1. What happens if you call a function and you don’t do anything <strong>with</strong> the<br />
result (i.e., you don’t assign it <strong>to</strong> a variable or use it as part of a larger<br />
expression)?<br />
2. What happens if you use a function <strong>with</strong>out a result as part of an expression,<br />
such as newLine() + 7?