forked from csev/py4e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04-functions.html
807 lines (799 loc) · 50.4 KB
/
04-functions.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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
<!DOCTYPE html>
<head>
<!--<script type="text/javascript" src="https://trinket.io/js/trinket.js"></script>-->
<link rel="stylesheet" href="trinket/base.css" type="text/css" />
<link rel="stylesheet" href="trinket/trinket.css" type="text/css" />
<link rel="stylesheet" href="trinket/font-awesome.min.css" type="text/css" />
<style type="text/css">
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { color: #008000; } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { color: #008000; font-weight: bold; } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
<style>
/*Temporary Fix for Font Awesome ApplicatonManifest offline Cache */
@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot');
src: url('../fonts/fontawesome-webfont.eot') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2') format('woff2'), url('../fonts/fontawesome-webfont.woff') format('woff'), url('../fonts/fontawesome-webfont.ttf') format('truetype'), url('../fonts/fontawesome-webfont.svg') format('svg');
font-weight: normal;
font-style: normal;
}
</style>
</head>
<body class="loggedout">
<div class="main-content">
<div class="nav-wrapper">
<nav class="top-bar" data-topbar data-topbar data-options="is_hover: false">
<ul class="title-area">
<li class="name">
<a href="/">
<img src="https://trinket.io/img/trinket-logo.png" alt="Hosted by Trinket" />
</a>
</li>
<li class="toggle-topbar menu-icon"><a href="#"><span></span></a></li>
</ul>
<section class="top-bar-section">
<ul class="right">
<li><a href="http://pythonlearn.com"><i class="fa fa-star"></i> PythonLearn</a></li>
<li><a href="https://trinket.io"><i class="fa fa-star"></i> Trinket</a></li>
<li><a href="https://hourofpython.com"><i class="fa fa-graduation-cap"></i> Hour of Python</a></li>
</ul>
</section>
</nav>
</div>
<div class="booktoc sticky">
<nav class="top-bar" data-topbar="" role="navigation">
<ul class="title-area">
<li class="name">
<h1 class="no-anchor"><a href="#">Python for Everyone</a></h1>
</li>
<li class="toggle-topbar"><a href="#"><span>Menu</span></a></li>
</ul>
<section class="top-bar-section">
<ul class="left">
<li class="has-dropdown not-click">
<a href="#">Chapters</a>
<ul class="dropdown">
<li class="title back js-generated">
<h5><a href="javascript:void(0)">Back</a></h5></li>
<li class="parent-link hide-for-medium-up"><a class="parent-link js-generated" href="#">Chapters</a></li>
<li><a href="index.html">See All Chapters</a></li>
<li><a href="01-intro.html">Chapter 1: Introduction</a></li>
<li><a href="02-variables.html">Chapter 2: Variables</a></li>
<li><a href="03-conditional.html">Chapter 3: Conditionals</a></li>
<li><a href="04-functions.html">Chapter 4: Functions</a></li>
<li><a href="05-iterations.html">Chapter 5: Iterations</a></li>
<li><a href="06-strings.html">Chapter 6: Strings</a></li>
<li><a href="07-files.html">Chapter 7: Files</a></li>
<li><a href="08-lists.html">Chapter 8: Lists</a></li>
<li><a href="09-dictionaries.html">Chapter 9: Dictionaries</a></li>
<li><a href="10-tuples.html">Chapter 10: Tuples</a></li>
<li><a href="11-regex.html">Chapter 11: Regex</a></li>
<li><a href="12-network.html">Chapter 12: Networked Programs</a></li>
<li><a href="13-web.html">Chapter 13: Python and Web Services</a></li>
<li><a href="14-objects.html">Chapter 14: Object Orientation</a></li>
<li><a href="15-database.html">Chapter 15: Python and Databases</a></li>
<li><a href="16-viz.html">Chapter 16: Data Vizualization</a></li>
</ul>
</li>
</ul>
</section>
</nav>
</div>
<div class="bookchapter">
<div class="row">
<div class="columns small-12">
<h1 id="functions">Functions</h1>
<h2 id="function-calls">Function calls</h2>
<p></p>
<p>In the context of programming, a <em>function</em> 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 <em>function call</em>:</p>
<div class="sourceCode" id="cb1"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">type</span>(<span class="dv">32</span>)</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="op"><</span><span class="kw">class</span> <span class="st">'int'</span><span class="op">></span></span></code></pre></div>
<p>The name of the function is <code>type</code>. The expression in
parentheses is called the <em>argument</em> 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 <code>type</code> function,
is the type of the argument.</p>
<p></p>
<p>It is common to say that a function “takes” an argument and “returns”
a result. The result is called the <em>return value</em>.</p>
<p> </p>
<h2 id="built-in-functions">Built-in functions</h2>
<p>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.</p>
<p>The <code>max</code> and <code>min</code> functions give us the
largest and smallest values in a list, respectively:</p>
<div class="sourceCode" id="cb2"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">max</span>(<span class="st">'Hello world'</span>)</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="co">'w'</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">min</span>(<span class="st">'Hello world'</span>)</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="co">' '</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span></span></code></pre></div>
<p>The <code>max</code> function tells us the “largest character” in the
string (which turns out to be the letter “w”) and the <code>min</code>
function shows us the smallest character (which turns out to be a
space).</p>
<p>Another very common built-in function is the <code>len</code>
function which tells us how many items are in its argument. If the
argument to <code>len</code> is a string, it returns the number of
characters in the string.</p>
<div class="sourceCode" id="cb3"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">len</span>(<span class="st">'Hello world'</span>)</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a><span class="dv">11</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span></span></code></pre></div>
<p>These functions are not limited to looking at strings. They can
operate on any set of values, as we will see in later chapters.</p>
<p>You should treat the names of built-in functions as reserved words
(i.e., avoid using “max” as a variable name).</p>
<h2 id="type-conversion-functions">Type conversion functions</h2>
<p> </p>
<p>Python also provides built-in functions that convert values from one
type to another. The <code>int</code> function takes any value and
converts it to an integer, if it can, or complains otherwise:</p>
<p> </p>
<div class="sourceCode" id="cb4"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">int</span>(<span class="st">'32'</span>)</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a><span class="dv">32</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">int</span>(<span class="st">'Hello'</span>)</span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a><span class="pp">ValueError</span>: invalid literal <span class="cf">for</span> <span class="bu">int</span>() <span class="cf">with</span> base <span class="dv">10</span>: <span class="st">'Hello'</span></span></code></pre></div>
<p><code>int</code> can convert floating-point values to integers, but
it doesn’t round off; it chops off the fraction part:</p>
<div class="sourceCode" id="cb5"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">int</span>(<span class="fl">3.99999</span>)</span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="dv">3</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">int</span>(<span class="op">-</span><span class="fl">2.3</span>)</span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a><span class="op">-</span><span class="dv">2</span></span></code></pre></div>
<p><code>float</code> converts integers and strings to floating-point
numbers:</p>
<p> </p>
<div class="sourceCode" id="cb6"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">float</span>(<span class="dv">32</span>)</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="fl">32.0</span></span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">float</span>(<span class="st">'3.14159'</span>)</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a><span class="fl">3.14159</span></span></code></pre></div>
<p>Finally, <code>str</code> converts its argument to a string:</p>
<p> </p>
<div class="sourceCode" id="cb7"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">str</span>(<span class="dv">32</span>)</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="co">'32'</span></span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">str</span>(<span class="fl">3.14159</span>)</span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a><span class="co">'3.14159'</span></span></code></pre></div>
<h2 id="math-functions">Math functions</h2>
<p> </p>
<p>Python has a <code>math</code> module that provides most of the
familiar mathematical functions. Before we can use the module, we have
to import it:</p>
<div class="sourceCode" id="cb8"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="im">import</span> math</span></code></pre></div>
<p>This statement creates a <em>module object</em> named math. If you
print the module object, you get some information about it:</p>
<div class="sourceCode" id="cb9"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">print</span>(math)</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="op"><</span>module <span class="st">'math'</span> (built<span class="op">-</span><span class="kw">in</span>)<span class="op">></span></span></code></pre></div>
<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 <em>dot notation</em>.</p>
<p></p>
<div class="sourceCode" id="cb10"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> ratio <span class="op">=</span> signal_power <span class="op">/</span> noise_power</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> decibels <span class="op">=</span> <span class="dv">10</span> <span class="op">*</span> math.log10(ratio)</span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> radians <span class="op">=</span> <span class="fl">0.7</span></span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> height <span class="op">=</span> math.sin(radians)</span></code></pre></div>
<p>The first example computes the logarithm base 10 of the
signal-to-noise ratio. The math module also provides a function called
<code>log</code> that computes logarithms base e.</p>
<p> </p>
<p>The second example finds the sine of <code>radians</code>. The name
of the variable is a hint that <code>sin</code> and the other
trigonometric functions (<code>cos</code>, <code>tan</code>, etc.) take
arguments in radians. To convert from degrees to radians, divide by 360
and multiply by <span class="math inline">2<em>π</em></span>:</p>
<div class="sourceCode" id="cb11"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> degrees <span class="op">=</span> <span class="dv">45</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> radians <span class="op">=</span> degrees <span class="op">/</span> <span class="fl">360.0</span> <span class="op">*</span> <span class="dv">2</span> <span class="op">*</span> math.pi</span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> math.sin(radians)</span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a><span class="fl">0.7071067811865476</span></span></code></pre></div>
<p>The expression <code>math.pi</code> gets the variable <code>pi</code>
from the math module. The value of this variable is an approximation of
<span class="math inline"><em>π</em></span>, accurate to about 15
digits.</p>
<p></p>
<p>If you know your trigonometry, you can check the previous result by
comparing it to the square root of two divided by two:</p>
<p> </p>
<div class="sourceCode" id="cb12"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> math.sqrt(<span class="dv">2</span>) <span class="op">/</span> <span class="fl">2.0</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a><span class="fl">0.7071067811865476</span></span></code></pre></div>
<h2 id="random-numbers">Random numbers</h2>
<p> </p>
<p>Given the same inputs, most computer programs generate the same
outputs every time, so they are said to be <em>deterministic</em>.
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.</p>
<p>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 <em>algorithms</em> that generate <em>pseudorandom</em>
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.</p>
<p> </p>
<p>The <code>random</code> module provides functions that generate
pseudorandom numbers (which I will simply call “random” from here
on).</p>
<p> </p>
<p>The function <code>random</code> returns a random float between 0.0
and 1.0 (including 0.0 but not 1.0). Each time you call
<code>random</code>, you get the next number in a long series. To see a
sample, run this loop:</p>
<div class="sourceCode" id="cb13"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> random</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> i <span class="kw">in</span> <span class="bu">range</span>(<span class="dv">10</span>):</span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a> x <span class="op">=</span> random.random()</span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(x)</span></code></pre></div>
<p>This program produces the following list of 10 random numbers between
0.0 and up to but not including 1.0.</p>
<pre><code>0.11132867921152356
0.5950949227890241
0.04820265884996877
0.841003109276478
0.997914947094958
0.04842330803368111
0.7416295948208405
0.510535245390327
0.27447040171978143
0.028511805472785867</code></pre>
<p><strong>Exercise 1: Run the program on your system and see what
numbers you get. Run the program more than once and see what numbers you
get.</strong></p>
<p>The <code>random</code> function is only one of many functions that
handle random numbers. The function <code>randint</code> takes the
parameters <code>low</code> and <code>high</code>, and returns an
integer between <code>low</code> and <code>high</code> (including
both).</p>
<p> </p>
<div class="sourceCode" id="cb15"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> random.randint(<span class="dv">5</span>, <span class="dv">10</span>)</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a><span class="dv">5</span></span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> random.randint(<span class="dv">5</span>, <span class="dv">10</span>)</span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a><span class="dv">9</span></span></code></pre></div>
<p>To choose an element from a sequence at random, you can use
<code>choice</code>:</p>
<p> </p>
<div class="sourceCode" id="cb16"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> t <span class="op">=</span> [<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>]</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> random.choice(t)</span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a><span class="dv">2</span></span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> random.choice(t)</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a><span class="dv">3</span></span></code></pre></div>
<p>The <code>random</code> module also provides functions to generate
random values from continuous distributions including Gaussian,
exponential, gamma, and a few more.</p>
<h2 id="adding-new-functions">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 <em>function
definition</em> 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.</p>
<p> </p>
<p>Here is an example:</p>
<div class="sourceCode" id="cb17"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> print_lyrics():</span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">"I'm a lumberjack, and I'm okay."</span>)</span>
<span id="cb17-3"><a href="#cb17-3" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">'I sleep all night and I work all day.'</span>)</span></code></pre></div>
<p><code>def</code> 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.</p>
<p> </p>
<p>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.</p>
<p> </p>
<p>The first line of the function definition is called the
<em>header</em>; the rest is called the <em>body</em>. 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.</p>
<p></p>
<p>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:</p>
<div class="sourceCode" id="cb18"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="kw">def</span> print_lyrics():</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>... <span class="bu">print</span>(<span class="st">"I'm a lumberjack, and I'm okay."</span>)</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>... <span class="bu">print</span>(<span class="st">'I sleep all night and I work all day.'</span>)</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a>...</span></code></pre></div>
<p>To end the function, you have to enter an empty line (this is not
necessary in a script).</p>
<p>Defining a function creates a variable with the same name.</p>
<div class="sourceCode" id="cb19"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">print</span>(print_lyrics)</span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a><span class="op"><</span>function print_lyrics at <span class="bn">0xb7e99e9c</span><span class="op">></span></span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">print</span>(<span class="bu">type</span>(print_lyrics))</span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a><span class="op"><</span><span class="kw">class</span> <span class="st">'function'</span><span class="op">></span></span></code></pre></div>
<p>The value of <code>print_lyrics</code> is a <em>function object</em>,
which has type “function”.</p>
<p> </p>
<p>The syntax for calling the new function is the same as for built-in
functions:</p>
<div class="sourceCode" id="cb20"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> print_lyrics()</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a>I<span class="st">'m a lumberjack, and I'</span>m okay.</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a>I sleep <span class="bu">all</span> night <span class="kw">and</span> I work <span class="bu">all</span> day.</span></code></pre></div>
<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>
<div class="sourceCode" id="cb21"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> repeat_lyrics():</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a> print_lyrics()</span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a> print_lyrics()</span></code></pre></div>
<p>And then call <code>repeat_lyrics</code>:</p>
<div class="sourceCode" id="cb22"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> repeat_lyrics()</span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a>I<span class="st">'m a lumberjack, and I'</span>m okay.</span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a>I sleep <span class="bu">all</span> night <span class="kw">and</span> I work <span class="bu">all</span> day.</span>
<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a>I<span class="st">'m a lumberjack, and I'</span>m okay.</span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a>I sleep <span class="bu">all</span> night <span class="kw">and</span> I work <span class="bu">all</span> day.</span></code></pre></div>
<p>But that’s not really how the song goes.</p>
<h2 id="definitions-and-uses">Definitions and uses</h2>
<p></p>
<p>Pulling together the code fragments from the previous section, the
whole program looks like this:</p>
<script type="text/javascript">(function(d,l,s,i,c){function n(e){e=e.nextSibling;return (!e||e.nodeType!=3)?e:n(e);};function r(f){/in/.test(d.readyState) ? setTimeout(function(){r(f);},9):f()};l=d.getElementsByTagName('script');s=l[l.length-1];r(function(){i=n(s),c=n(i);i.setAttribute('data-src','https://trinket.io/tools/1.0/jekyll/embed/python3#code='+encodeURIComponent(c.nodeValue.replace(/^\s+|\s+$/g,'')));});})(document)</script>
<iframe width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" class="lazyload" allowfullscreen>
</iframe>
<!--
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()
# Code: http://www.py4e.com/code3/lyrics.py
# Or select Download from this trinket's left-hand menu
-->
<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
get executed until the function is called, and the function definition
generates no output.</p>
<p></p>
<p>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.</p>
<p><strong>Exercise 2: 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.</strong></p>
<p><strong>Exercise 3: 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?</strong></p>
<h2 id="flow-of-execution">Flow of execution</h2>
<p></p>
<p>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 <em>flow of execution</em>.</p>
<p>Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to bottom.</p>
<p>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.</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,
executes all 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 execute the statements in another function. But while executing
that new function, the program might have to execute 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>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.</p>
<h2 id="parameters-and-arguments">Parameters and arguments</h2>
<p> </p>
<p>Some of the built-in functions we have seen require arguments. For
example, when you call <code>math.sin</code> you pass a number as an
argument. Some functions take more than one argument:
<code>math.pow</code> takes two, the base and the exponent.</p>
<p>Inside the function, the arguments are assigned to variables called
<em>parameters</em>. Here is an example of a user-defined function that
takes an argument:</p>
<p></p>
<div class="sourceCode" id="cb23"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> print_twice(bruce):</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(bruce)</span>
<span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(bruce)</span></code></pre></div>
<p>This function assigns the argument to a parameter named
<code>bruce</code>. 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>
<div class="sourceCode" id="cb24"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> print_twice(<span class="st">'Spam'</span>)</span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a>Spam</span>
<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a>Spam</span>
<span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> print_twice(<span class="dv">17</span>)</span>
<span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a><span class="dv">17</span></span>
<span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a><span class="dv">17</span></span>
<span id="cb24-7"><a href="#cb24-7" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="im">import</span> math</span>
<span id="cb24-8"><a href="#cb24-8" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> print_twice(math.pi)</span>
<span id="cb24-9"><a href="#cb24-9" aria-hidden="true" tabindex="-1"></a><span class="fl">3.141592653589793</span></span>
<span id="cb24-10"><a href="#cb24-10" aria-hidden="true" tabindex="-1"></a><span class="fl">3.141592653589793</span></span></code></pre></div>
<p>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>:</p>
<p></p>
<div class="sourceCode" id="cb25"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> print_twice(<span class="st">'Spam '</span><span class="op">*</span><span class="dv">4</span>)</span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a>Spam Spam Spam Spam</span>
<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a>Spam Spam Spam Spam</span>
<span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> print_twice(math.cos(math.pi))</span>
<span id="cb25-5"><a href="#cb25-5" aria-hidden="true" tabindex="-1"></a><span class="op">-</span><span class="fl">1.0</span></span>
<span id="cb25-6"><a href="#cb25-6" aria-hidden="true" tabindex="-1"></a><span class="op">-</span><span class="fl">1.0</span></span></code></pre></div>
<p>The argument is evaluated before the function is called, so in the
examples the expressions <code>'Spam '*4</code> and
<code>math.cos(math.pi)</code> are only evaluated once.</p>
<p></p>
<p>You can also use a variable as an argument:</p>
<div class="sourceCode" id="cb26"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> michael <span class="op">=</span> <span class="st">'Eric, the half a bee.'</span></span>
<span id="cb26-2"><a href="#cb26-2" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> print_twice(michael)</span>
<span id="cb26-3"><a href="#cb26-3" aria-hidden="true" tabindex="-1"></a>Eric, the half a bee.</span>
<span id="cb26-4"><a href="#cb26-4" aria-hidden="true" tabindex="-1"></a>Eric, the half a bee.</span></code></pre></div>
<p>The name of the variable we pass as an argument
(<code>michael</code>) has nothing to do with the name of the parameter
(<code>bruce</code>). It doesn’t matter what the value was called back
home (in the caller); here in <code>print_twice</code>, we call
everybody <code>bruce</code>.</p>
<h2 id="fruitful-functions-and-void-functions">Fruitful functions and
void functions</h2>
<p> </p>
<p>Some of the functions we are using, such as the math functions, yield
results; for lack of a better name, I call them <em>fruitful
functions</em>. Other functions, like <code>print_twice</code>, perform
an action but don’t return a value. They are called <em>void
functions</em>.</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>
<div class="sourceCode" id="cb27"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true" tabindex="-1"></a>x <span class="op">=</span> math.cos(radians)</span>
<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a>golden <span class="op">=</span> (math.sqrt(<span class="dv">5</span>) <span class="op">+</span> <span class="dv">1</span>) <span class="op">/</span> <span class="dv">2</span></span></code></pre></div>
<p>When you call a function in interactive mode, Python displays the
result:</p>
<div class="sourceCode" id="cb28"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> math.sqrt(<span class="dv">5</span>)</span>
<span id="cb28-2"><a href="#cb28-2" aria-hidden="true" tabindex="-1"></a><span class="fl">2.23606797749979</span></span></code></pre></div>
<p>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!</p>
<div class="sourceCode" id="cb29"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb29-1"><a href="#cb29-1" aria-hidden="true" tabindex="-1"></a>math.sqrt(<span class="dv">5</span>)</span></code></pre></div>
<p>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.</p>
<p> </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 try to assign
the result to a variable, you get a special value called
<code>None</code>.</p>
<p> </p>
<div class="sourceCode" id="cb30"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> result <span class="op">=</span> print_twice(<span class="st">'Bing'</span>)</span>
<span id="cb30-2"><a href="#cb30-2" aria-hidden="true" tabindex="-1"></a>Bing</span>
<span id="cb30-3"><a href="#cb30-3" aria-hidden="true" tabindex="-1"></a>Bing</span>
<span id="cb30-4"><a href="#cb30-4" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">print</span>(result)</span>
<span id="cb30-5"><a href="#cb30-5" aria-hidden="true" tabindex="-1"></a><span class="va">None</span></span></code></pre></div>
<p>The value <code>None</code> is not the same as the string “None”. It
is a special value that has its own type:</p>
<div class="sourceCode" id="cb31"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb31-1"><a href="#cb31-1" aria-hidden="true" tabindex="-1"></a><span class="op">>>></span> <span class="bu">print</span>(<span class="bu">type</span>(<span class="va">None</span>))</span>
<span id="cb31-2"><a href="#cb31-2" aria-hidden="true" tabindex="-1"></a><span class="op"><</span><span class="kw">class</span> <span class="st">'NoneType'</span><span class="op">></span></span></code></pre></div>
<p>To return a result from a function, we use the <code>return</code>
statement in our function. For example, we could make a very simple
function called <code>addtwo</code> that adds two numbers together and
returns a result.</p>
<script type="text/javascript">(function(d,l,s,i,c){function n(e){e=e.nextSibling;return (!e||e.nodeType!=3)?e:n(e);};function r(f){/in/.test(d.readyState) ? setTimeout(function(){r(f);},9):f()};l=d.getElementsByTagName('script');s=l[l.length-1];r(function(){i=n(s),c=n(i);i.setAttribute('data-src','https://trinket.io/tools/1.0/jekyll/embed/python3#code='+encodeURIComponent(c.nodeValue.replace(/^\s+|\s+$/g,'')));});})(document)</script>
<iframe width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" class="lazyload" allowfullscreen>
</iframe>
<!--
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x)
# Code: http://www.py4e.com/code3/addtwo.py
# Or select Download from this trinket's left-hand menu
-->
<p>When this script executes, the <code>print</code> statement will
print out “8” because the <code>addtwo</code> function was called with 3
and 5 as arguments. Within the function, the parameters <code>a</code>
and <code>b</code> were 3 and 5 respectively. The function computed the
sum of the two numbers and placed it in the local function variable
named <code>added</code>. Then it used the <code>return</code> statement
to send the computed value back to the calling code as the function
result, which was assigned to the variable <code>x</code> and printed
out.</p>
<h2 id="why-functions">Why functions?</h2>
<p></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>
<li><p>Creating a new function gives you an opportunity to name a group
of statements, which makes your program easier to read, understand, and
debug.</p></li>
<li><p>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.</p></li>
<li><p>Dividing a long program into functions allows you to debug the
parts one at a time and then assemble them into a working
whole.</p></li>
<li><p>Well-designed functions are often useful for many programs. Once
you write and debug one, you can reuse it.</p></li>
</ul>
<p>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 <code>min</code> which takes a list of values as
its argument and returns the smallest value in the list.</p>
<h2 id="debugging">Debugging</h2>
<p></p>
<p>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.</p>
<p></p>
<p>Tabs and spaces are usually invisible, which makes them hard to
debug, so try to find an editor that manages indentation for you.</p>
<p>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.</p>
<p>Debugging can take a long time if you keep running the same incorrect
program over and over!</p>
<p>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!</p>
<h2 id="glossary">Glossary</h2>
<dl>
<dt>algorithm</dt>
<dd>
A general process for solving a category of problems.
</dd>
<dt>argument</dt>
<dd>
A value provided to a function when the function is called. This value
is assigned to the corresponding parameter in the function.
</dd>
<dt>body</dt>
<dd>
The sequence of statements inside a function definition.
</dd>
<dt>composition</dt>
<dd>
Using an expression as part of a larger expression, or a statement as
part of a larger statement.
</dd>
<dt>deterministic</dt>
<dd>
Pertaining to a program that does the same thing each time it runs,
given the same inputs.
</dd>
<dt>dot notation</dt>
<dd>
The syntax for calling a function in another module by specifying the
module name followed by a dot (period) and the function name.
</dd>
<dt>flow of execution</dt>
<dd>
The order in which statements are executed during a program run.
</dd>
<dt>fruitful function</dt>
<dd>
A function that returns a value.
</dd>
<dt>function</dt>
<dd>
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.
</dd>
<dt>function call</dt>
<dd>
A statement that executes a function. It consists of the function name
followed by an argument list.
</dd>
<dt>function definition</dt>
<dd>
A statement that creates a new function, specifying its name,
parameters, and the statements it executes.
</dd>
<dt>function object</dt>
<dd>
A value created by a function definition. The name of the function is a
variable that refers to a function object.
</dd>
<dt>header</dt>
<dd>
The first line of a function definition.
</dd>
<dt>import statement</dt>
<dd>
A statement that reads a module file and creates a module object.
</dd>
<dt>module object</dt>
<dd>
A value created by an <code>import</code> statement that provides access
to the data and code defined in a module.
</dd>
<dt>parameter</dt>
<dd>
A name used inside a function to refer to the value passed as an
argument.
</dd>
<dt>pseudorandom</dt>
<dd>
Pertaining to a sequence of numbers that appear to be random, but are
generated by a deterministic program.
</dd>
<dt>return value</dt>
<dd>
The result of a function. If a function call is used as an expression,
the return value is the value of the expression.
</dd>
<dt>void function</dt>
<dd>
A function that does not return a value.
</dd>
</dl>
<h2 id="exercises">Exercises</h2>
<p><strong>Exercise 4: What is the purpose of the “def” keyword in
Python?</strong></p>
<p>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</p>
<p><strong>Exercise 5: What will the following Python program print
out?</strong></p>
<div class="sourceCode" id="cb32"><pre
class="sourceCode python"><code class="sourceCode python"><span id="cb32-1"><a href="#cb32-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> fred():</span>
<span id="cb32-2"><a href="#cb32-2" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">"Zap"</span>)</span>
<span id="cb32-3"><a href="#cb32-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb32-4"><a href="#cb32-4" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> jane():</span>
<span id="cb32-5"><a href="#cb32-5" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">"ABC"</span>)</span>
<span id="cb32-6"><a href="#cb32-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb32-7"><a href="#cb32-7" aria-hidden="true" tabindex="-1"></a>jane()</span>
<span id="cb32-8"><a href="#cb32-8" aria-hidden="true" tabindex="-1"></a>fred()</span>
<span id="cb32-9"><a href="#cb32-9" aria-hidden="true" tabindex="-1"></a>jane()</span></code></pre></div>
<p>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</p>
<p><strong>Exercise 6: Rewrite your pay computation with time-and-a-half
for overtime and create a function called <code>computepay</code> which
takes two parameters (<code>hours</code> and
<code>rate</code>).</strong></p>
<pre><code>Enter Hours: 45
Enter Rate: 10
Pay: 475.0</code></pre>
<p><strong>Exercise 7: Rewrite the grade program from the previous
chapter using a function called <code>computegrade</code> that takes a
score as its parameter and returns a grade as a string.</strong></p>
<pre><code> Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F</code></pre>
<pre><code>Enter score: 0.95
A</code></pre>
<pre><code>Enter score: perfect
Bad score</code></pre>
<pre><code>Enter score: 10.0
Bad score</code></pre>
<pre><code>Enter score: 0.75
C</code></pre>
<pre><code>Enter score: 0.5
F</code></pre>
<p>Run the program repeatedly to test the various different values for
input.</p>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="trinket/jquery.min.js"></script>
<script type="text/javascript" src="trinket/jquery-ui.min.js"></script>
<script type="text/javascript" src="trinket/foundation.min.js"></script>
<script type="text/javascript" src="trinket/anchor.min.js"></script>
<script type="text/javascript" src="trinket/lazysizes.min.js"></script>
<script type="text/javascript" src='trinket/go.js'></script>
</body>