forked from csev/py4e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbook005.html
More file actions
520 lines (507 loc) · 36.8 KB
/
book005.html
File metadata and controls
520 lines (507 loc) · 36.8 KB
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="hevea 2.09" />
<link rel="stylesheet" type="text/css" href="book.css" />
<title>Functions</title>
</head>
<body>
<a href="book004.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="book006.html"><img src="next_motif.gif" alt="Next" /></a>
<hr />
<h1 class="chapter" id="sec45"><span class="c006">Chapter 4  Functions</span></h1>
<p><span class="c005">
</span><a id="funcchap"></a></p><span class="c005">
</span><h2 class="section" id="sec46"><span class="c006">4.1  Function calls</span></h2>
<p><span class="c005">
</span><a id="functionchap"></a><span class="c005">
</span><a id="hevea_default191"></a></p><p><span class="c006">In the context of programming, a <span class="c009">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.
We have already seen one example of a <span class="c009">function call</span>:</span></p><pre class="verbatim"><span class="c004">>>> type(32)
<type 'int'>
</span></pre><p><span class="c006">The name of the function is <span class="c001">type</span>. The expression in parentheses
is called the <span class="c009">argument</span> of the function. The argument is
a value or variable that we are passing into the function as input
to the function.
The result, for the <span class="c001">type</span> function, is the type of the argument.</span></p><p><a id="hevea_default192"></a></p><p><span class="c006">It is common to say that a function “takes” an argument and “returns”
a result. The result is called the <span class="c009">return value</span>.</span></p><p><a id="hevea_default193"></a><span class="c005">
</span><a id="hevea_default194"></a></p><span class="c005">
</span><h2 class="section" id="sec47"><span class="c006">4.2  Built-in functions</span></h2>
<p><span class="c006">Python provides a number of important built-in functions that
we can use without needing to provide the function definition.
The creators of Python wrote a set of functions
to solve common problems and included them in Python for us to use.</span></p><p><span class="c006">The <span class="c001">max</span> and <span class="c001">min</span> functions give us the largest and
smallest values in a list, respectively:</span></p><pre class="verbatim"><span class="c004">>>> max('Hello world')
'w'
>>> min('Hello world')
' '
>>>
</span></pre><p><span class="c006">The <span class="c001">max</span> function tells us the “largest character” in the
string (which turns out to be the letter “w”) and the <span class="c001">min</span>
function shows us the smallest character which turns out to be a
space.</span></p><p><span class="c006">Another very common built-in function is the <span class="c001">len</span> function
which tells us how many items are in its argument. If the argument
to <span class="c001">len</span> is a string, it returns the number of characters
in the string.</span></p><pre class="verbatim"><span class="c004">>>> len('Hello world')
11
>>>
</span></pre><p><span class="c006">These functions are not limited to looking at strings, they can operate
on any set of values as we will see in later chapters.</span></p><p><span class="c006">You should treat the names of built-in functions as reserved words (i.e.
avoid using “max” as a variable name).</span></p><span class="c005">
</span><h2 class="section" id="sec48"><span class="c006">4.3  Type conversion functions</span></h2>
<p><span class="c005">
</span><a id="hevea_default195"></a><span class="c005">
</span><a id="hevea_default196"></a></p><p><span class="c006">Python also provides built-in functions that convert values
from one type to another. The <span class="c001">int</span> function takes any value and
converts it to an integer, if it can, or complains otherwise:</span></p><p><a id="hevea_default197"></a><span class="c005">
</span><a id="hevea_default198"></a></p><pre class="verbatim"><span class="c004">>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
</span></pre><p><span class="c006"><span class="c001">int</span> can convert floating-point values to integers, but it
doesn’t round off; it chops off the fraction part:</span></p><pre class="verbatim"><span class="c004">>>> int(3.99999)
3
>>> int(-2.3)
-2
</span></pre><p><span class="c006"><span class="c001">float</span> converts integers and strings to floating-point
numbers:</span></p><p><a id="hevea_default199"></a><span class="c005">
</span><a id="hevea_default200"></a></p><pre class="verbatim"><span class="c004">>>> float(32)
32.0
>>> float('3.14159')
3.14159
</span></pre><p><span class="c006">Finally, <span class="c001">str</span> converts its argument to a string:</span></p><p><a id="hevea_default201"></a><span class="c005">
</span><a id="hevea_default202"></a></p><pre class="verbatim"><span class="c004">>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
</span></pre><span class="c005">
</span><h2 class="section" id="sec49"><span class="c006">4.4  Random numbers</span></h2>
<p><a id="hevea_default203"></a><span class="c005">
</span><a id="hevea_default204"></a><span class="c005">
</span><a id="hevea_default205"></a><span class="c005">
</span><a id="hevea_default206"></a></p><p><span class="c006">Given the same inputs, most computer programs generate the same
outputs every time, so they are said to be <span class="c009">deterministic</span>.
Determinism is usually a good thing, since we expect the same
calculation to yield the same result. For some applications, though,
we want the computer to be unpredictable. Games are an obvious
example, but there are more.</span></p><p><span class="c006">Making a program truly nondeterministic turns out to be not so easy,
but there are ways to make it at least seem nondeterministic. One of
them is to use <span class="c009">algorithms</span> that generate <span class="c009">pseudorandom</span> numbers.
Pseudorandom numbers are not truly random because they are generated
by a deterministic computation, but just by looking at the numbers it
is all but impossible to distinguish them from random.</span></p><p><a id="hevea_default207"></a><span class="c005">
</span><a id="hevea_default208"></a></p><p><span class="c006">The <span class="c001">random</span> module provides functions that generate
pseudorandom numbers (which I will simply call “random” from
here on).</span></p><p><a id="hevea_default209"></a><span class="c005">
</span><a id="hevea_default210"></a></p><p><span class="c006">The function <span class="c001">random</span> returns a random float
between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you
call <span class="c001">random</span>, you get the next number in a long series. To see a
sample, run this loop:</span></p><pre class="verbatim"><span class="c004">import random
for i in range(10):
x = random.random()
print x
</span></pre><p><span class="c006">This program produces the following list of 10 random numbers
between 0.0 and up to but not including 1.0.</span></p><pre class="verbatim"><span class="c004">0.301927091705
0.513787075867
0.319470430881
0.285145917252
0.839069045123
0.322027080731
0.550722110248
0.366591677812
0.396981483964
0.838116437404
</span></pre><div class="theorem"><span class="c006"><span class="c009">Exercise 1</span>  <em>
Run the program on your system and see what numbers you get.
Run the program more than once and see what numbers you get.
</em></span></div><p><span class="c006">The <span class="c001">random</span> function is only one of many
functions which handle random numbers.
The function <span class="c001">randint</span> takes parameters <span class="c001">low</span> and
<span class="c001">high</span> and returns an integer between <span class="c001">low</span> and
<span class="c001">high</span> (including both).</span></p><p><a id="hevea_default211"></a><span class="c005">
</span><a id="hevea_default212"></a></p><pre class="verbatim"><span class="c004">>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9
</span></pre><p><span class="c006">To choose an element from a sequence at random, you can use
<span class="c001">choice</span>:</span></p><p><a id="hevea_default213"></a><span class="c005">
</span><a id="hevea_default214"></a></p><pre class="verbatim"><span class="c004">>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3
</span></pre><p><span class="c006">The <span class="c001">random</span> module also provides functions to generate
random values from continuous distributions including
Gaussian, exponential, gamma, and a few more.</span></p><span class="c005">
</span><h2 class="section" id="sec50"><span class="c006">4.5  Math functions</span></h2>
<p><span class="c005">
</span><a id="hevea_default215"></a><span class="c005">
</span><a id="hevea_default216"></a><span class="c005">
</span><a id="hevea_default217"></a><span class="c005">
</span><a id="hevea_default218"></a></p><p><span class="c006">Python has a math <span class="c009">module</span> that provides most of the familiar
mathematical functions.
Before we can use the module, we have to import it:</span></p><pre class="verbatim"><span class="c004">>>> import math
</span></pre><p><span class="c006">This statement creates a <span class="c009">module object</span> named math. If
you print the module object, you get some information about it:</span></p><pre class="verbatim"><span class="c004">>>> print math
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
</span></pre><p><span class="c006">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="c009">dot notation</span>.</span></p><p><a id="hevea_default219"></a></p><pre class="verbatim"><span class="c004">>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
</span></pre><p><span class="c006">The first example computes the logarithm base 10 of the
signal-to-noise ratio. The math module also provides a
function called <span class="c001">log</span> that computes logarithms base <span class="c001">e</span>.</span></p><p><a id="hevea_default220"></a><span class="c005">
</span><a id="hevea_default221"></a><span class="c005">
</span><a id="hevea_default222"></a><span class="c005">
</span><a id="hevea_default223"></a><span class="c005">
</span><a id="hevea_default224"></a><span class="c005">
</span><a id="hevea_default225"></a></p><p><span class="c006">The second example finds the sine of <span class="c001">radians</span>. The name of the
variable is a hint that <span class="c001">sin</span> and the other trigonometric
functions (<span class="c001">cos</span>, <span class="c001">tan</span>, etc.) take arguments in radians. To
convert from degrees to radians, divide by 360 and multiply by 2
π:</span></p><pre class="verbatim"><span class="c004">>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187
</span></pre><p><span class="c006">The expression <span class="c001">math.pi</span> gets the variable <span class="c001">pi</span> from the math
module. The value of this variable is an approximation
of π, accurate to about 15 digits.</span></p><p><a id="hevea_default226"></a></p><p><span class="c006">If you know
your trigonometry, you can check the previous result by comparing it to
the square root of two divided by two:</span></p><p><a id="hevea_default227"></a><span class="c005">
</span><a id="hevea_default228"></a></p><pre class="verbatim"><span class="c004">>>> math.sqrt(2) / 2.0
0.707106781187
</span></pre><span class="c005">
</span><h2 class="section" id="sec51"><span class="c006">4.6  Adding new functions</span></h2>
<p><span class="c006">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="c009">function definition</span> specifies the name of a new function and
the sequence of statements that execute when the function is called.
Once we define a function, we can reuse the function over and over
throughout our program.</span></p><p><a id="hevea_default229"></a><span class="c005">
</span><a id="hevea_default230"></a><span class="c005">
</span><a id="hevea_default231"></a></p><p><span class="c006">Here is an example:</span></p><pre class="verbatim"><span class="c004">def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'
</span></pre><p><span class="c006"><span class="c001">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 some punctuation marks 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.</span></p><p><a id="hevea_default232"></a><span class="c005">
</span><a id="hevea_default233"></a><span class="c005">
</span><a id="hevea_default234"></a></p><p><span class="c006">The empty parentheses after the name indicate that this function
doesn’t take any arguments. Later we will build functions that
take arguments as their inputs.</span></p><p><a id="hevea_default235"></a><span class="c005">
</span><a id="hevea_default236"></a><span class="c005">
</span><a id="hevea_default237"></a><span class="c005">
</span><a id="hevea_default238"></a><span class="c005">
</span><a id="hevea_default239"></a></p><p><span class="c006">The first line of the function definition is called the <span class="c009">header</span>;
the rest is called the <span class="c009">body</span>. The header has to end with a colon
and the body has to be indented. By convention, the indentation is
always four spaces. The body can contain
any number of statements.</span></p><p><span class="c006">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.</span></p><p><a id="hevea_default240"></a></p><p><span class="c006">If you type a function definition in interactive mode, the interpreter
prints ellipses (<em>...</em>) to let you know that the definition
isn’t complete:</span></p><pre class="verbatim"><span class="c004">>>> def print_lyrics():
... print "I'm a lumberjack, and I'm okay."
... print 'I sleep all night and I work all day.'
...
</span></pre><p><span class="c006">To end the function, you have to enter an empty line (this is
not necessary in a script).</span></p><p><span class="c006">Defining a function creates a variable with the same name.</span></p><pre class="verbatim"><span class="c004">>>> print print_lyrics
<function print_lyrics at 0xb7e99e9c>
>>> print type(print_lyrics)
<type 'function'>
</span></pre><p><span class="c006">The value of <code>print_lyrics</code> is a <span class="c009">function object</span>, which
has type <code>'function'</code>.</span></p><p><a id="hevea_default241"></a><span class="c005">
</span><a id="hevea_default242"></a></p><p><span class="c006">The syntax for calling the new function is the same as
for built-in functions:</span></p><pre class="verbatim"><span class="c004">>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
</span></pre><p><span class="c006">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>:</span></p><pre class="verbatim"><span class="c004">def repeat_lyrics():
print_lyrics()
print_lyrics()
</span></pre><p><span class="c006">And then call <code>repeat_lyrics</code>:</span></p><pre class="verbatim"><span class="c004">>>> 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.
</span></pre><p><span class="c006">But that’s not really how the song goes.</span></p><span class="c005">
</span><h2 class="section" id="sec52"><span class="c006">4.7  Definitions and uses</span></h2>
<p><span class="c005">
</span><a id="hevea_default243"></a></p><p><span class="c006">Pulling together the code fragments from the previous section, the
whole program looks like this:</span></p><pre class="verbatim"><span class="c004">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()
</span></pre><p><span class="c006">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 get executed until the function is called, and
the function definition generates no output.</span></p><p><a id="hevea_default244"></a></p><p><span class="c006">As you might expect, you have to create a function before you can
execute it. In other words, the function definition has to be
executed before the first time it is called.</span></p><div class="theorem"><span class="c006"><span class="c009">Exercise 2</span>  <em>
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.
</em></span></div><div class="theorem"><span class="c006"><span class="c009">Exercise 3</span>  <em>
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?
</em></span></div><span class="c005">
</span><h2 class="section" id="sec53"><span class="c006">4.8  Flow of execution</span></h2>
<p><span class="c005">
</span><a id="hevea_default245"></a></p><p><span class="c006">In order to ensure that a function is defined before its first use,
you have to know the order in which statements are executed, which is
called the <span class="c009">flow of execution</span>.</span></p><p><span class="c006">Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to bottom.</span></p><p><span class="c006">Function <em>definitions</em> do not alter the flow of execution of the
program, but remember that statements inside the function are not
executed until the function is called.</span></p><p><span class="c006">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, executes all the statements there, and then comes back
to pick up where it left off.</span></p><p><span class="c006">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 execute the statements in another function. But while
executing that new function, the program might have to execute yet
another function!</span></p><p><span class="c006">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.</span></p><p><span class="c006">What’s the moral of this sordid tale? 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.</span></p><span class="c005">
</span><h2 class="section" id="sec54"><span class="c006">4.9  Parameters and arguments</span></h2>
<p><span class="c005">
</span><a id="parameters"></a><span class="c005">
</span><a id="hevea_default246"></a><span class="c005">
</span><a id="hevea_default247"></a><span class="c005">
</span><a id="hevea_default248"></a><span class="c005">
</span><a id="hevea_default249"></a></p><p><span class="c006">Some of the built-in functions we have seen require arguments. For
example, when you call <span class="c001">math.sin</span> you pass a number
as an argument. Some functions take more than one argument:
<span class="c001">math.pow</span> takes two, the base and the exponent.</span></p><p><span class="c006">Inside the function, the arguments are assigned to
variables called <span class="c009">parameters</span>. Here is an example of a
user-defined function that takes an argument:</span></p><p><a id="hevea_default250"></a></p><pre class="verbatim"><span class="c004">def print_twice(bruce):
print bruce
print bruce
</span></pre><p><span class="c006">This function assigns the argument to a parameter
named <span class="c001">bruce</span>. When the function is called, it prints the value of
the parameter (whatever it is) twice.</span></p><p><span class="c006">This function works with any value that can be printed.</span></p><pre class="verbatim"><span class="c004">>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
>>> print_twice(math.pi)
3.14159265359
3.14159265359
</span></pre><p><span class="c006">The same rules of composition that apply to built-in functions also
apply to user-defined functions, so we can use any kind of expression
as an argument for <code>print_twice</code>:</span></p><p><a id="hevea_default251"></a></p><pre class="verbatim"><span class="c004">>>> print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0
</span></pre><p><span class="c006">The argument is evaluated before the function is called, so
in the examples the expressions <code>'Spam '*4</code> and
<span class="c001">math.cos(math.pi)</span> are only evaluated once.</span></p><p><a id="hevea_default252"></a></p><p><span class="c006">You can also use a variable as an argument:</span></p><pre class="verbatim"><span class="c004">>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
</span></pre><p><span class="c006">The name of the variable we pass as an argument (<span class="c001">michael</span>) has
nothing to do with the name of the parameter (<span class="c001">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="c001">bruce</span>.</span></p><span class="c005">
</span><h2 class="section" id="sec55"><span class="c006">4.10  Fruitful functions and void functions</span></h2>
<p><a id="hevea_default253"></a><span class="c005">
</span><a id="hevea_default254"></a><span class="c005">
</span><a id="hevea_default255"></a><span class="c005">
</span><a id="hevea_default256"></a><span class="c005"> </span></p><p><span class="c006">Some of the functions we are using, such as the math functions, yield
results; for lack of a better name, I call them <span class="c009">fruitful
functions</span>. Other functions, like <code>print_twice</code>, perform an
action but don’t return a value. They are called <span class="c009">void
functions</span>.</span></p><p><span class="c006">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:</span></p><pre class="verbatim"><span class="c004">x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
</span></pre><p><span class="c006">When you call a function in interactive mode, Python displays
the result:</span></p><pre class="verbatim"><span class="c004">>>> math.sqrt(5)
2.2360679774997898
</span></pre><p><span class="c006">But in a script, if you call a fruitful function and do
not store the result of the function in a variable,
the return value vanishes into the mist!</span></p><pre class="verbatim"><span class="c004">math.sqrt(5)
</span></pre><p><span class="c006">This script computes the square root of 5, but since it doesn’t store
the result in a variable or display the result, it is not very useful.</span></p><p><a id="hevea_default257"></a><span class="c005">
</span><a id="hevea_default258"></a></p><p><span class="c006">Void functions might display something on the screen or have some
other effect, but they don’t have a return value. If you try to
assign the result to a variable, you get a special value called
<span class="c001">None</span>.</span></p><p><a id="hevea_default259"></a><span class="c005">
</span><a id="hevea_default260"></a></p><pre class="verbatim"><span class="c004">>>> result = print_twice('Bing')
Bing
Bing
>>> print result
None
</span></pre><p><span class="c006">The value <span class="c001">None</span> is not the same as the string <code>'None'</code>.
It is a special value that has its own type:</span></p><pre class="verbatim"><span class="c004">>>> print type(None)
<type 'NoneType'>
</span></pre><p><span class="c006">To return a result from a function, we use the <span class="c001">return</span> statement
in our function. For example, we could make a very
simple function called <span class="c001">addtwo</span>
that adds two numbers together and return a result.</span></p><pre class="verbatim"><span class="c004">def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print x
</span></pre><p><span class="c006">When this script executes, the <span class="c001">print</span> statement will print out “8”
because the <span class="c001">addtwo</span> function was called with 3 and 5 as arguments.
Within the function the parameters <span class="c001">a</span> and <span class="c001">b</span> were 3 and 5
respectively. The function computed the sum of the two numbers and placed
it in the local function variable named <span class="c001">added</span>
and used the <span class="c001">return</span> statement
to send the computed value back to the calling code
as the function result which was assigned
to the variable <span class="c001">x</span> and printed out.</span></p><span class="c005">
</span><h2 class="section" id="sec56"><span class="c006">4.11  Why functions?</span></h2>
<p><span class="c005">
</span><a id="hevea_default261"></a></p><p><span class="c006">It may not be clear why it is worth the trouble to divide
a program into functions. There are several reasons:</span></p><ul class="itemize"><li class="li-itemize"><span class="c006">Creating a new function gives you an opportunity to name a group
of statements, which makes your program easier to read, understand
and debug.</span></li><li class="li-itemize"><span class="c006">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.</span></li><li class="li-itemize"><span class="c006">Dividing a long program into functions allows you to debug the
parts one at a time and then assemble them into a working whole.</span></li><li class="li-itemize"><span class="c006">Well-designed functions are often useful for many programs.
Once you write and debug one, you can reuse it.</span></li></ul><p><span class="c006">Throughout the rest of the book, often we will use a function definition to
explain a concept. Part of the skill of creating and using functions is
to have a function properly capture an idea such as “find the smallest
value in a list of values”. Later we will show you code that finds
the smallest in a list of values and we will present it to you as a function
named <span class="c001">min</span> which takes a list of values as its argument and
returns the smallest value in the list.</span></p><span class="c005">
</span><h2 class="section" id="sec57"><span class="c006">4.12  Debugging</span></h2>
<p><span class="c005">
</span><a id="editor"></a><span class="c005">
</span><a id="hevea_default262"></a></p><p><span class="c006">If you are using a text editor to write your scripts, you might
run into problems with spaces and tabs. The best way to avoid
these problems is to use spaces exclusively (no tabs). Most text
editors that know about Python do this by default, but some
don’t.</span></p><p><a id="hevea_default263"></a></p><p><span class="c006">Tabs and spaces are usually invisible, which makes them
hard to debug, so try to find an editor that manages indentation
for you.</span></p><p><span class="c006">Also, don’t forget to save your program before you run it. Some
development environments do this automatically, but some don’t.
In that case the program you are looking at in the text editor
is not the same as the program you are running.</span></p><p><span class="c006">Debugging can take a long time if you keep running the same,
incorrect, program over and over!</span></p><p><span class="c006">Make sure that the code you are looking at is the code you are running.
If you’re not sure, put something like <code>print 'hello'</code> at the
beginning of the program and run it again. If you don’t see
<code>hello</code>, you’re not running the right program!</span></p><span class="c005">
</span><h2 class="section" id="sec58"><span class="c006">4.13  Glossary</span></h2>
<dl class="description"><dt class="dt-description"><span class="c010">algorithm:</span></dt><dd class="dd-description"><span class="c006"> A general process for solving a category of
problems.
</span><a id="hevea_default264"></a></dd><dt class="dt-description"><span class="c010">argument:</span></dt><dd class="dd-description"><span class="c006"> A value provided to a function when the function is called.
This value is assigned to the corresponding parameter in the function.
</span><a id="hevea_default265"></a></dd><dt class="dt-description"><span class="c010">body:</span></dt><dd class="dd-description"><span class="c006"> The sequence of statements inside a function definition.
</span><a id="hevea_default266"></a></dd><dt class="dt-description"><span class="c010">composition:</span></dt><dd class="dd-description"><span class="c006"> Using an expression as part of a larger expression,
or a statement as part of a larger statement.
</span><a id="hevea_default267"></a></dd><dt class="dt-description"><span class="c010">deterministic:</span></dt><dd class="dd-description"><span class="c006"> Pertaining to a program that does the same
thing each time it runs, given the same inputs.
</span><a id="hevea_default268"></a></dd><dt class="dt-description"><span class="c010">dot notation:</span></dt><dd class="dd-description"><span class="c006"> The syntax for calling a function in another
module by specifying the module name followed by a dot (period) and
the function name.
</span><a id="hevea_default269"></a></dd><dt class="dt-description"><span class="c010">flow of execution:</span></dt><dd class="dd-description"><span class="c006"> The order in which statements are executed during
a program run.
</span><a id="hevea_default270"></a></dd><dt class="dt-description"><span class="c010">fruitful function:</span></dt><dd class="dd-description"><span class="c006"> A function that returns a value.
</span><a id="hevea_default271"></a></dd><dt class="dt-description"><span class="c010">function:</span></dt><dd class="dd-description"><span class="c006"> 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.
</span><a id="hevea_default272"></a></dd><dt class="dt-description"><span class="c010">function call:</span></dt><dd class="dd-description"><span class="c006"> A statement that executes a function. It
consists of the function name followed by an argument list.
</span><a id="hevea_default273"></a></dd><dt class="dt-description"><span class="c010">function definition:</span></dt><dd class="dd-description"><span class="c006"> A statement that creates a new function,
specifying its name, parameters, and the statements it executes.
</span><a id="hevea_default274"></a></dd><dt class="dt-description"><span class="c010">function object:</span></dt><dd class="dd-description"><span class="c006"> A value created by a function definition.
The name of the function is a variable that refers to a function
object.
</span><a id="hevea_default275"></a></dd><dt class="dt-description"><span class="c010">header:</span></dt><dd class="dd-description"><span class="c006"> The first line of a function definition.
</span><a id="hevea_default276"></a></dd><dt class="dt-description"><span class="c010">import statement:</span></dt><dd class="dd-description"><span class="c006"> A statement that reads a module file and creates
a module object.
</span><a id="hevea_default277"></a><span class="c005">
</span><a id="hevea_default278"></a></dd><dt class="dt-description"><span class="c010">module object:</span></dt><dd class="dd-description"><span class="c006"> A value created by an <span class="c001">import</span> statement
that provides access to the data and code defined in a module.
</span><a id="hevea_default279"></a></dd><dt class="dt-description"><span class="c010">parameter:</span></dt><dd class="dd-description"><span class="c006"> A name used inside a function to refer to the value
passed as an argument.
</span><a id="hevea_default280"></a></dd><dt class="dt-description"><span class="c010">pseudorandom:</span></dt><dd class="dd-description"><span class="c006"> Pertaining to a sequence of numbers that appear
to be random, but are generated by a deterministic program.
</span><a id="hevea_default281"></a></dd><dt class="dt-description"><span class="c010">return value:</span></dt><dd class="dd-description"><span class="c006"> The result of a function. If a function call
is used as an expression, the return value is the value of
the expression.
</span><a id="hevea_default282"></a></dd><dt class="dt-description"><span class="c010">void function:</span></dt><dd class="dd-description"><span class="c006"> A function that doesn’t return a value.
</span><a id="hevea_default283"></a></dd></dl><span class="c005">
</span><h2 class="section" id="sec59"><span class="c006">4.14  Exercises</span></h2>
<div class="theorem"><span class="c006"><span class="c009">Exercise 4</span>  <em>
What is the purpose of the "def" keyword in Python?</em></span><p><span class="c006"><em>a) It is slang that means "the following code is really cool"<br />
b) It indicates the start of a function<br />
c) It indicates that the following indented section of code is to be stored for later<br />
d) b and c are both true<br />
e) None of the above
</em></span></p></div><div class="theorem"><span class="c006"><span class="c009">Exercise 5</span>  <em>
What will the following Python program print out?</em></span><pre class="verbatim"><span class="c004"><em>def fred():
print "Zap"
def jane():
print "ABC"
jane()
fred()
jane()
</em></span></pre><p><span class="c006"><em>a) Zap ABC jane fred jane<br />
b) Zap ABC Zap<br />
c) ABC Zap jane<br />
d) ABC Zap ABC<br />
e) Zap Zap Zap
</em></span></p></div><div class="theorem"><span class="c006"><span class="c009">Exercise 6</span>  <em>
Rewrite your pay computation with time-and-a-half for overtime
and create a function called <span class="c001">computepay</span> which takes
two parameters (<span class="c001">hours</span> and <span class="c001">rate</span>).</em></span><pre class="verbatim"><span class="c006"><em>Enter Hours: 45
Enter Rate: 10
Pay: 475.0
</em></span></pre></div><div class="theorem"><span class="c006"><span class="c009">Exercise 7</span>  <em>
Rewrite the grade program from the previous chapter
using a function called <span class="c001">computegrade</span> that takes
a score as its parameter and returns a grade as a string.</em></span><pre class="verbatim"><span class="c006"><em>Score Grade
> 0.9 A
> 0.8 B
> 0.7 C
> 0.6 D
<= 0.6 F
Program Execution:
Enter score: 0.95
A
Enter score: perfect
Bad score
Enter score: 10.0
Bad score
Enter score: 0.75
C
Enter score: 0.5
F
</em></span></pre><p><span class="c006"><em>Run the program repeatedly to test the various different values
for input.
</em></span></p></div><span class="c005">
</span><hr />
<a href="book004.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="book006.html"><img src="next_motif.gif" alt="Next" /></a>
</body>
</html>