forked from bailiangrui/git-basics-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththinkpython2004.html
645 lines (613 loc) · 42.4 KB
/
thinkpython2004.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<meta name="generator" content="hevea 2.09">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="thinkpython2.css">
<title>Functions</title>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><strong>Think Python</strong> - How to Think like a Computer Scientist (2e) <em>by Allen B. Downey</em></a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><a href="http://greenteapress.com/thinkpython2/html/index.html"><span class="glyphicon glyphicon glyphicon-book" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2003.html"><span class="glyphicon glyphicon glyphicon-menu-left" aria-hidden="true"></span></a></li>
<li><a href="index.html"><span class="glyphicon glyphicon glyphicon-home" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2005.html"><span class="glyphicon glyphicon glyphicon-menu-right" aria-hidden="true"></span></a></li>
<li><a href="http://amzn.to/1VUYQUU"><span class="glyphicon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span></a></li>
</ul>
<div>
</div><!-- /.container-fluid -->
</nav>
<table>
<tr>
<td valign="top" width="100" bgcolor="#b6459a" id="col-left">
</td>
<td valign="top" id="content">
<p>
<h1 class="chapter" id="sec26">Chapter 3  Functions</h1>
<p>
<a id="funcchap"></a></p><p>In the context of programming, a <span class="c010">function</span> is a named sequence of
statements that performs a computation. When you define a function,
you specify the name and the sequence of statements. Later, you can
“call” the function by name.
<a id="hevea_default146"></a></p>
<h2 class="section" id="sec27">3.1  Function calls</h2>
<p>
<a id="functionchap"></a>
<a id="hevea_default147"></a></p><p>We have already seen one example of a <span class="c010">function call</span>:</p><pre class="verbatim">>>> type(42)
<class 'int'>
</pre><p>The name of the function is <span class="c004">type</span>. The expression in parentheses
is called the <span class="c010">argument</span> of the function. The result, for this
function, is the type of the argument.
<a id="hevea_default148"></a></p><p>It is common to say that a function “takes” an argument and “returns”
a result. The result is also called the <span class="c010">return value</span>.
<a id="hevea_default149"></a>
<a id="hevea_default150"></a></p><p>Python provides functions that convert values
from one type to another. The <span class="c004">int</span> function takes any value and
converts it to an integer, if it can, or complains otherwise:
<a id="hevea_default151"></a>
<a id="hevea_default152"></a>
<a id="hevea_default153"></a>
<a id="hevea_default154"></a></p><pre class="verbatim">>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
</pre><p><span class="c004">int</span> can convert floating-point values to integers, but it
doesn’t round off; it chops off the fraction part:</p><pre class="verbatim">>>> int(3.99999)
3
>>> int(-2.3)
-2
</pre><p><span class="c004">float</span> converts integers and strings to floating-point
numbers:
<a id="hevea_default155"></a>
<a id="hevea_default156"></a></p><pre class="verbatim">>>> float(32)
32.0
>>> float('3.14159')
3.14159
</pre><p>Finally, <span class="c004">str</span> converts its argument to a string:
<a id="hevea_default157"></a>
<a id="hevea_default158"></a></p><pre class="verbatim">>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
</pre>
<h2 class="section" id="sec28">3.2  Math functions</h2>
<p>
<a id="hevea_default159"></a>
<a id="hevea_default160"></a></p><p>Python has a math module that provides most of the familiar
mathematical functions. A <span class="c010">module</span> is a file that contains a
collection of related functions.
<a id="hevea_default161"></a>
<a id="hevea_default162"></a></p><p>Before we can use the functions in a module, we have to import it with
an <span class="c010">import statement</span>:</p><pre class="verbatim">>>> import math
</pre><p>This statement creates a <span class="c010">module object</span> named math. If
you display the module object, you get some information about it:</p><pre class="verbatim">>>> math
<module 'math' (built-in)>
</pre><p>The module object contains the functions and variables defined in the
module. To access one of the functions, you have to specify the name
of the module and the name of the function, separated by a dot (also
known as a period). This format is called <span class="c010">dot notation</span>.
<a id="hevea_default163"></a></p><pre class="verbatim">>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
</pre><p>The first example uses <code>math.log10</code> to compute
a signal-to-noise ratio in decibels (assuming that <code>signal_power</code> and
<code>noise_power</code> are defined). The math module also provides <span class="c004">log</span>,
which computes logarithms base <span class="c004">e</span>.
<a id="hevea_default164"></a>
<a id="hevea_default165"></a>
<a id="hevea_default166"></a>
<a id="hevea_default167"></a>
<a id="hevea_default168"></a>
<a id="hevea_default169"></a></p><p>The second example finds the sine of <span class="c004">radians</span>. The name of the
variable is a hint that <span class="c004">sin</span> and the other trigonometric
functions (<span class="c004">cos</span>, <span class="c004">tan</span>, etc.) take arguments in radians. To
convert from degrees to radians, divide by 180 and multiply by
π:</p><pre class="verbatim">>>> degrees = 45
>>> radians = degrees / 180.0 * math.pi
>>> math.sin(radians)
0.707106781187
</pre><p>The expression <span class="c004">math.pi</span> gets the variable <span class="c004">pi</span> from the math
module. Its value is a floating-point approximation
of π, accurate to about 15 digits.
<a id="hevea_default170"></a></p><p>If you know
trigonometry, you can check the previous result by comparing it to
the square root of two divided by two:
<a id="hevea_default171"></a>
<a id="hevea_default172"></a></p><pre class="verbatim">>>> math.sqrt(2) / 2.0
0.707106781187
</pre>
<h2 class="section" id="sec29">3.3  Composition</h2>
<p>
<a id="hevea_default173"></a></p><p>So far, we have looked at the elements of a program—variables,
expressions, and statements—in isolation, without talking about how to
combine them.</p><p>One of the most useful features of programming languages is their
ability to take small building blocks and <span class="c010">compose</span> them. For
example, the argument of a function can be any kind of expression,
including arithmetic operators:</p><pre class="verbatim">x = math.sin(degrees / 360.0 * 2 * math.pi)
</pre><p>And even function calls:</p><pre class="verbatim">x = math.exp(math.log(x+1))
</pre><p>Almost anywhere you can put a value, you can put an arbitrary
expression, with one exception: the left side of an assignment
statement has to be a variable name. Any other expression on the left
side is a syntax error (we will see exceptions to this rule
later).</p><pre class="verbatim">>>> minutes = hours * 60 # right
>>> hours * 60 = minutes # wrong!
SyntaxError: can't assign to operator
</pre><p><a id="hevea_default174"></a>
<a id="hevea_default175"></a></p>
<h2 class="section" id="sec30">3.4  Adding new functions</h2>
<p>So far, we have only been using the functions that come with Python,
but it is also possible to add new functions.
A <span class="c010">function definition</span> specifies the name of a new function and
the sequence of statements that run when the function is called.
<a id="hevea_default176"></a>
<a id="hevea_default177"></a>
<a id="hevea_default178"></a></p><p>Here is an example:</p><pre class="verbatim">def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")
</pre><p><span class="c004">def</span> is a keyword that indicates that this is a function
definition. The name of the function is <code>print_lyrics</code>. The
rules for function names are the same as for variable names: letters,
numbers and underscore are legal, but the first character
can’t be a number. You can’t use a keyword as the name of a function,
and you should avoid having a variable and a function with the same
name.
<a id="hevea_default179"></a>
<a id="hevea_default180"></a>
<a id="hevea_default181"></a></p><p>The empty parentheses after the name indicate that this function
doesn’t take any arguments.
<a id="hevea_default182"></a>
<a id="hevea_default183"></a>
<a id="hevea_default184"></a>
<a id="hevea_default185"></a>
<a id="hevea_default186"></a></p><p>The first line of the function definition is called the <span class="c010">header</span>;
the rest is called the <span class="c010">body</span>. The header has to end with a colon
and the body has to be indented. By convention, indentation is
always four spaces. The body can contain
any number of statements.</p><p>The strings in the print statements are enclosed in double
quotes. Single quotes and double quotes do the same thing;
most people use single quotes except in cases like this where
a single quote (which is also an apostrophe) appears in the string.</p><p>All quotation marks (single and double)
must be “straight quotes”, usually
located next to Enter on the keyboard. “Curly quotes”, like
the ones in this sentence, are not legal in Python.</p><p>If you type a function definition in interactive mode, the interpreter
prints dots (<span class="c004">...</span>) to let you know that the definition
isn’t complete:
<a id="hevea_default187"></a></p><pre class="verbatim">>>> def print_lyrics():
... print("I'm a lumberjack, and I'm okay.")
... print("I sleep all night and I work all day.")
...
</pre><p>To end the function, you have to enter an empty line.</p><p>Defining a function creates a <span class="c010">function object</span>, which
has type <code>function</code>:
<a id="hevea_default188"></a>
<a id="hevea_default189"></a></p><pre class="verbatim">>>> print(print_lyrics)
<function print_lyrics at 0xb7e99e9c>
>>> type(print_lyrics)
<class 'function'>
</pre><p>The syntax for calling the new function is the same as
for built-in functions:</p><pre class="verbatim">>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
</pre><p>Once you have defined a function, you can use it inside another
function. For example, to repeat the previous refrain, we could write
a function called <code>repeat_lyrics</code>:</p><pre class="verbatim">def repeat_lyrics():
print_lyrics()
print_lyrics()
</pre><p>And then call <code>repeat_lyrics</code>:</p><pre class="verbatim">>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
</pre><p>But that’s not really how the song goes.</p>
<h2 class="section" id="sec31">3.5  Definitions and uses</h2>
<p>
<a id="hevea_default190"></a></p><p>Pulling together the code fragments from the previous section, the
whole program looks like this:</p><pre class="verbatim">def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
</pre><p>This program contains two function definitions: <code>print_lyrics</code> and
<code>repeat_lyrics</code>. Function definitions get executed just like other
statements, but the effect is to create function objects. The statements
inside the function do not run until the function is called, and
the function definition generates no output.
<a id="hevea_default191"></a></p><p>As you might expect, you have to create a function before you can
run it. In other words, the function definition has to run
before the function gets called.</p><p>As an exercise, move the last line of this program
to the top, so the function call appears before the definitions. Run
the program and see what error
message you get.</p><p>Now move the function call back to the bottom
and move the definition of <code>print_lyrics</code> after the definition of
<code>repeat_lyrics</code>. What happens when you run this program?</p>
<h2 class="section" id="sec32">3.6  Flow of execution</h2>
<p>
<a id="hevea_default192"></a></p><p>To ensure that a function is defined before its first use,
you have to know the order statements run in, which is
called the <span class="c010">flow of execution</span>.</p><p>Execution always begins at the first statement of the program.
Statements are run one at a time, in order from top to bottom.</p><p>Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function don’t
run until the function is called.</p><p>A function call is like a detour in the flow of execution. Instead of
going to the next statement, the flow jumps to the body of
the function, runs the statements there, and then comes back
to pick up where it left off.</p><p>That sounds simple enough, until you remember that one function can
call another. While in the middle of one function, the program might
have to run the statements in another function. Then, while
running that new function, the program might have to run yet
another function!</p><p>Fortunately, Python is good at keeping track of where it is, so each
time a function completes, the program picks up where it left off in
the function that called it. When it gets to the end of the program,
it terminates.</p><p>In summary, when you read a program, you
don’t always want to read from top to bottom. Sometimes it makes
more sense if you follow the flow of execution.</p>
<h2 class="section" id="sec33">3.7  Parameters and arguments</h2>
<p>
<a id="parameters"></a>
<a id="hevea_default193"></a>
<a id="hevea_default194"></a>
<a id="hevea_default195"></a>
<a id="hevea_default196"></a></p><p>Some of the functions we have seen require arguments. For
example, when you call <span class="c004">math.sin</span> you pass a number
as an argument. Some functions take more than one argument:
<span class="c004">math.pow</span> takes two, the base and the exponent.</p><p>Inside the function, the arguments are assigned to
variables called <span class="c010">parameters</span>. Here is a definition for
a function that takes an argument:
<a id="hevea_default197"></a></p><pre class="verbatim">def print_twice(bruce):
print(bruce)
print(bruce)
</pre><p>This function assigns the argument to a parameter
named <span class="c004">bruce</span>. When the function is called, it prints the value of
the parameter (whatever it is) twice.</p><p>This function works with any value that can be printed.</p><pre class="verbatim">>>> print_twice('Spam')
Spam
Spam
>>> print_twice(42)
42
42
>>> print_twice(math.pi)
3.14159265359
3.14159265359
</pre><p>The same rules of composition that apply to built-in functions also
apply to programmer-defined functions, so we can use any kind of expression
as an argument for <code>print_twice</code>:
<a id="hevea_default198"></a>
<a id="hevea_default199"></a>
<a id="hevea_default200"></a></p><pre class="verbatim">>>> print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0
</pre><p>The argument is evaluated before the function is called, so
in the examples the expressions <code>'Spam '*4</code> and
<span class="c004">math.cos(math.pi)</span> are only evaluated once.
<a id="hevea_default201"></a></p><p>You can also use a variable as an argument:</p><pre class="verbatim">>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
</pre><p>The name of the variable we pass as an argument (<span class="c004">michael</span>) has
nothing to do with the name of the parameter (<span class="c004">bruce</span>). It
doesn’t matter what the value was called back home (in the caller);
here in <code>print_twice</code>, we call everybody <span class="c004">bruce</span>.</p>
<h2 class="section" id="sec34">3.8  Variables and parameters are local</h2>
<p>
<a id="hevea_default202"></a>
<a id="hevea_default203"></a></p><p>When you create a variable inside a function, it is <span class="c010">local</span>,
which means that it only
exists inside the function. For example:
<a id="hevea_default204"></a></p><pre class="verbatim">def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
</pre><p>This function takes two arguments, concatenates them, and prints
the result twice. Here is an example that uses it:
<a id="hevea_default205"></a></p><pre class="verbatim">>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.
</pre><p>When <code>cat_twice</code> terminates, the variable <span class="c004">cat</span>
is destroyed. If we try to print it, we get an exception:
<a id="hevea_default206"></a>
<a id="hevea_default207"></a></p><pre class="verbatim">>>> print(cat)
NameError: name 'cat' is not defined
</pre><p>Parameters are also local.
For example, outside <code>print_twice</code>, there is no
such thing as <span class="c004">bruce</span>.
<a id="hevea_default208"></a></p>
<h2 class="section" id="sec35">3.9  Stack diagrams</h2>
<p>
<a id="stackdiagram"></a>
<a id="hevea_default209"></a>
<a id="hevea_default210"></a>
<a id="hevea_default211"></a></p><p>To keep track of which variables can be used where, it is sometimes
useful to draw a <span class="c010">stack diagram</span>. Like state diagrams, stack
diagrams show the value of each variable, but they also show the
function each variable belongs to.
<a id="hevea_default212"></a>
<a id="hevea_default213"></a></p><p>Each function is represented by a <span class="c010">frame</span>. A frame is a box with
the name of a function beside it and the parameters and variables of
the function inside it. The stack diagram for the previous example is
shown in Figure <a href="thinkpython2004.html#fig.stack">3.1</a>.</p><blockquote class="figure"><div class="center"><hr class="c019"></div>
<div class="center"><img src="images/thinkpython2002.png"></div>
<div class="caption"><table class="c001 cellpading0"><tr><td class="c018">Figure 3.1: Stack diagram.</td></tr>
</table></div>
<a id="fig.stack"></a>
<div class="center"><hr class="c019"></div></blockquote><p>The frames are arranged in a stack that indicates which function
called which, and so on. In this example, <code>print_twice</code>
was called by <code>cat_twice</code>, and <code>cat_twice</code> was called by
<code>__main__</code>, which is a special name for the topmost frame. When
you create a variable outside of any function, it belongs to
<code>__main__</code>.</p><p>Each parameter refers to the same value as its corresponding
argument. So, <span class="c004">part1</span> has the same value as
<span class="c004">line1</span>, <span class="c004">part2</span> has the same value as <span class="c004">line2</span>,
and <span class="c004">bruce</span> has the same value as <span class="c004">cat</span>.</p><p>If an error occurs during a function call, Python prints the
name of the function, the name of the function that called
it, and the name of the function that called <em>that</em>, all the
way back to <code>__main__</code>.</p><p>For example, if you try to access <span class="c004">cat</span> from within
<code>print_twice</code>, you get a <span class="c004">NameError</span>:</p><pre class="verbatim">Traceback (innermost last):
File "test.py", line 13, in __main__
cat_twice(line1, line2)
File "test.py", line 5, in cat_twice
print_twice(cat)
File "test.py", line 9, in print_twice
print(cat)
NameError: name 'cat' is not defined
</pre><p>This list of functions is called a <span class="c010">traceback</span>. It tells you what
program file the error occurred in, and what line, and what functions
were executing at the time. It also shows the line of code that
caused the error.
<a id="hevea_default214"></a></p><p>The order of the functions in the traceback is the same as the
order of the frames in the stack diagram. The function that is
currently running is at the bottom.</p>
<h2 class="section" id="sec36">3.10  Fruitful functions and void functions</h2>
<p>
<a id="hevea_default215"></a>
<a id="hevea_default216"></a>
<a id="hevea_default217"></a>
<a id="hevea_default218"></a> </p><p>Some of the functions we have used, such as the math functions, return
results; for lack of a better name, I call them <span class="c010">fruitful
functions</span>. Other functions, like <code>print_twice</code>, perform an
action but don’t return a value. They are called <span class="c010">void
functions</span>.</p><p>When you call a fruitful function, you almost always
want to do something with the result; for example, you might
assign it to a variable or use it as part of an expression:</p><pre class="verbatim">x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
</pre><p>When you call a function in interactive mode, Python displays
the result:</p><pre class="verbatim">>>> math.sqrt(5)
2.2360679774997898
</pre><p>But in a script, if you call a fruitful function all by itself,
the return value is lost forever!</p><pre class="verbatim">math.sqrt(5)
</pre><p>This script computes the square root of 5, but since it doesn’t store
or display the result, it is not very useful.
<a id="hevea_default219"></a>
<a id="hevea_default220"></a></p><p>Void functions might display something on the screen or have some
other effect, but they don’t have a return value. If you
assign the result to a variable, you get a special value called
<span class="c004">None</span>.
<a id="hevea_default221"></a>
<a id="hevea_default222"></a></p><pre class="verbatim">>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None
</pre><p>The value <span class="c004">None</span> is not the same as the string <code>'None'</code>.
It is a special value that has its own type:</p><pre class="verbatim">>>> type(None)
<class 'NoneType'>
</pre><p>The functions we have written so far are all void. We will start
writing fruitful functions in a few chapters.
<a id="hevea_default223"></a>
<a id="hevea_default224"></a></p>
<h2 class="section" id="sec37">3.11  Why functions?</h2>
<p>
<a id="hevea_default225"></a></p><p>It may not be clear why it is worth the trouble to divide
a program into functions. There are several reasons:</p><ul class="itemize"><li class="li-itemize">Creating a new function gives you an opportunity to name a group
of statements, which makes your program easier to read and debug.</li><li class="li-itemize">Functions can make a program smaller by eliminating repetitive
code. Later, if you make a change, you only have
to make it in one place.</li><li class="li-itemize">Dividing a long program into functions allows you to debug the
parts one at a time and then assemble them into a working whole.</li><li class="li-itemize">Well-designed functions are often useful for many programs.
Once you write and debug one, you can reuse it.</li></ul>
<h2 class="section" id="sec38">3.12  Debugging</h2>
<p>One of the most important skills you will acquire is debugging.
Although it can be frustrating, debugging is one of the most
intellectually rich, challenging, and interesting parts of
programming.
<a id="hevea_default226"></a>
<a id="hevea_default227"></a></p><p>In some ways debugging is like detective work. You are confronted
with clues and you have to infer the processes and events that led
to the results you see.</p><p>Debugging is also like an experimental science. Once you have an idea
about what is going wrong, you modify your program and try again. If
your hypothesis was correct, you can predict the result of the
modification, and you take a step closer to a working program. If
your hypothesis was wrong, you have to come up with a new one. As
Sherlock Holmes pointed out, “When you have eliminated the
impossible, whatever remains, however improbable, must be the truth.”
(A. Conan Doyle, <em>The Sign of Four</em>)
<a id="hevea_default228"></a>
<a id="hevea_default229"></a></p><p>For some people, programming and debugging are the same thing. That
is, programming is the process of gradually debugging a program until
it does what you want. The idea is that you should start with a
working program and make small modifications,
debugging them as you go.</p><p>For example, Linux is an operating system that contains millions of
lines of code, but it started out as a simple program Linus Torvalds
used to explore the Intel 80386 chip. According to Larry Greenfield,
“One of Linus’s earlier projects was a program that would switch
between printing AAAA and BBBB. This later evolved to Linux.”
(<em>The Linux Users’ Guide</em> Beta Version 1).
<a id="hevea_default230"></a></p>
<h2 class="section" id="sec39">3.13  Glossary</h2>
<dl class="description"><dt class="dt-description"><span class="c010">function:</span></dt><dd class="dd-description"> A named sequence of statements that performs some
useful operation. Functions may or may not take arguments and may or
may not produce a result.
<a id="hevea_default231"></a></dd><dt class="dt-description"><span class="c010">function definition:</span></dt><dd class="dd-description"> A statement that creates a new function,
specifying its name, parameters, and the statements it contains.
<a id="hevea_default232"></a></dd><dt class="dt-description"><span class="c010">function object:</span></dt><dd class="dd-description"> A value created by a function definition.
The name of the function is a variable that refers to a function
object.
<a id="hevea_default233"></a></dd><dt class="dt-description"><span class="c010">header:</span></dt><dd class="dd-description"> The first line of a function definition.
<a id="hevea_default234"></a></dd><dt class="dt-description"><span class="c010">body:</span></dt><dd class="dd-description"> The sequence of statements inside a function definition.
<a id="hevea_default235"></a></dd><dt class="dt-description"><span class="c010">parameter:</span></dt><dd class="dd-description"> A name used inside a function to refer to the value
passed as an argument.
<a id="hevea_default236"></a></dd><dt class="dt-description"><span class="c010">function call:</span></dt><dd class="dd-description"> A statement that runs a function. It
consists of the function name followed by an argument list in
parentheses.
<a id="hevea_default237"></a></dd><dt class="dt-description"><span class="c010">argument:</span></dt><dd class="dd-description"> A value provided to a function when the function is called.
This value is assigned to the corresponding parameter in the function.
<a id="hevea_default238"></a></dd><dt class="dt-description"><span class="c010">local variable:</span></dt><dd class="dd-description"> A variable defined inside a function. A local
variable can only be used inside its function.
<a id="hevea_default239"></a></dd><dt class="dt-description"><span class="c010">return value:</span></dt><dd class="dd-description"> The result of a function. If a function call
is used as an expression, the return value is the value of
the expression.
<a id="hevea_default240"></a></dd><dt class="dt-description"><span class="c010">fruitful function:</span></dt><dd class="dd-description"> A function that returns a value.
<a id="hevea_default241"></a></dd><dt class="dt-description"><span class="c010">void function:</span></dt><dd class="dd-description"> A function that always returns <span class="c004">None</span>.
<a id="hevea_default242"></a></dd><dt class="dt-description"><span class="c010"><span class="c004">None</span>:</span></dt><dd class="dd-description"> A special value returned by void functions.
<a id="hevea_default243"></a>
<a id="hevea_default244"></a></dd><dt class="dt-description"><span class="c010">module:</span></dt><dd class="dd-description"> A file that contains a
collection of related functions and other definitions.
<a id="hevea_default245"></a></dd><dt class="dt-description"><span class="c010">import statement:</span></dt><dd class="dd-description"> A statement that reads a module file and creates
a module object.
<a id="hevea_default246"></a>
<a id="hevea_default247"></a></dd><dt class="dt-description"><span class="c010">module object:</span></dt><dd class="dd-description"> A value created by an <span class="c004">import</span> statement
that provides access to the values defined in a module.
<a id="hevea_default248"></a></dd><dt class="dt-description"><span class="c010">dot notation:</span></dt><dd class="dd-description"> The syntax for calling a function in another
module by specifying the module name followed by a dot (period) and
the function name.
<a id="hevea_default249"></a></dd><dt class="dt-description"><span class="c010">composition:</span></dt><dd class="dd-description"> Using an expression as part of a larger expression,
or a statement as part of a larger statement.
<a id="hevea_default250"></a></dd><dt class="dt-description"><span class="c010">flow of execution:</span></dt><dd class="dd-description"> The order statements run in.
<a id="hevea_default251"></a></dd><dt class="dt-description"><span class="c010">stack diagram:</span></dt><dd class="dd-description"> A graphical representation of a stack of functions,
their variables, and the values they refer to.
<a id="hevea_default252"></a></dd><dt class="dt-description"><span class="c010">frame:</span></dt><dd class="dd-description"> A box in a stack diagram that represents a function call.
It contains the local variables and parameters of the function.
<a id="hevea_default253"></a>
<a id="hevea_default254"></a></dd><dt class="dt-description"><span class="c010">traceback:</span></dt><dd class="dd-description"> A list of the functions that are executing,
printed when an exception occurs.
<a id="hevea_default255"></a></dd></dl>
<h2 class="section" id="sec40">3.14  Exercises</h2>
<div class="theorem"><span class="c010">Exercise 1</span>  
<a id="hevea_default256"></a>
<a id="hevea_default257"></a><p><em>Write a function named <code>right_justify</code> that takes a string
named <span class="c004">s</span> as a parameter and prints the string with enough
leading spaces so that the last letter of the string is in column 70
of the display.</em></p><pre class="verbatim"><em>>>> right_justify('monty')
monty
</em></pre><p><em>Hint: Use string concatenation and repetition. Also,
Python provides a built-in function called <span class="c004">len</span> that
returns the length of a string, so the value of <code>len('monty')</code> is 5.</em></p></div><div class="theorem"><span class="c010">Exercise 2</span>  
<a id="hevea_default258"></a>
<a id="hevea_default259"></a><p><em>A function object is a value you can assign to a variable
or pass as an argument. For example, <code>do_twice</code> is a function
that takes a function object as an argument and calls it twice:</em></p><pre class="verbatim"><em>def do_twice(f):
f()
f()
</em></pre><p><em>Here’s an example that uses <code>do_twice</code> to call a function
named <code>print_spam</code> twice.</em></p><pre class="verbatim"><em>def print_spam():
print('spam')
do_twice(print_spam)
</em></pre><ol class="enumerate" type=1><li class="li-enumerate"><em>Type this example into a script and test it.</em></li><li class="li-enumerate"><em>Modify <code>do_twice</code> so that it takes two arguments, a
function object and a value, and calls the function twice,
passing the value as an argument.</em></li><li class="li-enumerate"><em>Copy the definition of
<code>print_twice</code> from earlier in this chapter to your script.</em></li><li class="li-enumerate"><em>Use the modified version of <code>do_twice</code> to call
<code>print_twice</code> twice, passing <code>'spam'</code> as an argument.</em></li><li class="li-enumerate"><em>Define a new function called
<code>do_four</code> that takes a function object and a value
and calls the function four times, passing the value
as a parameter. There should be only
two statements in the body of this function, not four.</em></li></ol><p><em>Solution: </em><a href="http://thinkpython2.com/code/do_four.py"><em><span class="c004">http://thinkpython2.com/code/do_four.py</span></em></a><em>.</em></p></div><div class="theorem"><span class="c010">Exercise 3</span>  <p><em>Note: This exercise should be
done using only the statements and other features we have learned so
far. </em></p><ol class="enumerate" type=1><li class="li-enumerate"><em>Write a function that draws a grid like the following:
</em><a id="hevea_default260"></a><pre class="verbatim"><em>+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
</em></pre><p><em>Hint: to print more than one value on a line, you can print
a comma-separated sequence of values:</em></p><pre class="verbatim"><em>print('+', '-')
</em></pre><p><em>By default, <span class="c004">print</span> advances to the next line, but you
can override that behavior and put a space at the end, like this:</em></p><pre class="verbatim"><em>print('+', end=' ')
print('-')
</em></pre><p><em>The output of these statements is <code>'+ -'</code>.</em></p><p><em>A <span class="c004">print</span> statement with no argument ends the current line and
goes to the next line.</em></p></li><li class="li-enumerate"><em>Write a function that draws a similar grid
with four rows and four columns.</em></li></ol><p><em>Solution: </em><a href="http://thinkpython2.com/code/grid.py"><em><span class="c004">http://thinkpython2.com/code/grid.py</span></em></a><em>.
Credit: This exercise is based on an exercise in Oualline, </em>Practical C Programming, Third Edition<em>, O’Reilly Media, 1997.</em></p></div>
<p>
</td>
<td width=130 valign="top" id="col-right">
<p>
<h4>Are you using one of our books in a class?</h4> We'd like to know
about it. Please consider filling out <a href="http://spreadsheets.google.com/viewform?formkey=dC0tNUZkMjBEdXVoRGljNm9FRmlTMHc6MA" onClick="javascript: pageTracker._trackPageview('/outbound/survey');">this short survey</a>.
<p>
<br>
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491938455/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491938455&linkCode=as2&tag=greenteapre01-20&linkId=2JJH4SWCAVVYSQHO">Think DSP</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491938455" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491938455/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491938455&linkCode=as2&tag=greenteapre01-20&linkId=CTV7PDT7E5EGGJUM"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491938455&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491938455" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491929561/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491929561&linkCode=as2&tag=greenteapre01-20&linkId=ZY6MAYM33ZTNSCNZ">Think Java</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491929561" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491929561/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491929561&linkCode=as2&tag=greenteapre01-20&linkId=PT77ANWARUNNU3UK"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491929561&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491929561" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449370780/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449370780&linkCode=as2&tag=greenteapre01-20">Think Bayes</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449370780" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449370780/ref=as_li_qf_sp_asin_il?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449370780&linkCode=as2&tag=greenteapre01-20"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1449370780&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449370780" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491939362/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491939362&linkCode=as2&tag=greenteapre01-20&linkId=FJKSQ3IHEMY2F2VA">Think Python 2e</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491939362" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491939362/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491939362&linkCode=as2&tag=greenteapre01-20&linkId=ZZ454DLQ3IXDHNHX"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491939362&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491939362" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1491907339/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491907339&linkCode=as2&tag=greenteapre01-20&linkId=O7WYM6H6YBYUFNWU">Think Stats 2e</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491907339" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1491907339/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491907339&linkCode=as2&tag=greenteapre01-20&linkId=JVSYKQHYSUIEYRHL"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491907339&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491907339" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449314635/ref=as_li_tf_tl?ie=UTF8&tag=greenteapre01-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1449314635">Think Complexity</a><img class="c003" src="http://www.assoc-amazon.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449314635" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449314635/ref=as_li_tf_il?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449314635&linkCode=as2&tag=greenteapre01-20"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1449314635&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://www.assoc-amazon.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449314635" width="1" height="1" border="0" alt="">
</td>
</tr>
</table>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><strong>Think Python</strong> - How to Think like a Computer Scientist (2e) <em>by Allen B. Downey</em></a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><a href="http://greenteapress.com/thinkpython2/html/index.html"><span class="glyphicon glyphicon glyphicon-book" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2003.html"><span class="glyphicon glyphicon glyphicon-menu-left" aria-hidden="true"></span></a></li>
<li><a href="index.html"><span class="glyphicon glyphicon glyphicon-home" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2005.html"><span class="glyphicon glyphicon glyphicon-menu-right" aria-hidden="true"></span></a></li>
<li><a href="http://amzn.to/1VUYQUU"><span class="glyphicon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span></a></li>
</ul>
<div>
</div><!-- /.container-fluid -->
</nav></body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</html>