-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathfunctions.html
executable file
·1300 lines (1131 loc) · 62.9 KB
/
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>4. Functions — How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)</title>
<link rel="stylesheet" href="_static/style.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="_static/codemirrorEdited.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="_static/pywindowCodemirrorC.js"></script>
<script type="text/javascript" src="_static/skulpt.min.js"></script>
<script type="text/javascript" src="_static/skulpt-stdlib.js"></script>
<script type="text/javascript" src="_static/aopsmods.js"></script>
<link rel="copyright" title="Copyright" href="copyright.html" />
<link rel="top" title="How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)" href="index.html" />
<link rel="next" title="5. Conditionals" href="conditionals.html" />
<link rel="prev" title="3. Hello, little turtles!" href="hello_little_turtles.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="conditionals.html" title="5. Conditionals"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="hello_little_turtles.html" title="3. Hello, little turtles!"
accesskey="P">previous</a> |</li>
<li><a href="index.html">How to Think Like a Computer Scientist: Learning with Python 3 (AoPS Edition)</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="body">
<div class="line-block">
<div class="line"><br /></div>
</div>
<div class="section" id="functions">
<h1>4. Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h1>
<div class="section" id="index-0">
<span id="id1"></span><h2>4.1. Functions<a class="headerlink" href="#index-0" title="Permalink to this headline">¶</a></h2>
<p>In Python, a <strong>function</strong> is a named sequence of statements
that belong together. Their primary purpose is to help us
organize programs into chunks that match how we think about
the problem.</p>
<p>The syntax for a <strong>function definition</strong> is:</p>
<div id="functiondef" class="pywindow" >
<div id="functiondef_code_div" style="display: block">
<textarea rows="2" id="functiondef_code" class="active_code" prefixcode="undefined">
def NAME( PARAMETERS ):
STATEMENTS</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['functiondef_code'] = false;
pythonTool.readOnlyFlags['functiondef_code'] = true;
</script>
<div id='functiondef_error'></div>
<pre id="functiondef_suffix" style="display:none">
</pre>
</div>
<p>We can make up any names we want for the functions we create, except that
we can’t use a name that is a Python keyword, and the names must follow the rules
for legal identifiers. By convention, we like to use all lowercase for function names,
with words separated by underscores, such as <tt class="docutils literal"><span class="pre">draw_square</span></tt>.</p>
<p>There can be any number of statements inside the function, but they have to be
indented from the <tt class="docutils literal"><span class="pre">def</span></tt>. In the examples in this book, we will use the
standard indentation of four spaces. Function definitions are the second of
several <strong>compound statements</strong> we will see, all of which have the same
pattern:</p>
<ol class="arabic simple">
<li>A header line which begins with a keyword and ends with a colon.</li>
<li>A <strong>body</strong> consisting of one or more Python statements, each
indented the same amount — we strongly recommend 4 spaces — from
the header line.</li>
</ol>
<p>We’ve already seen the <tt class="docutils literal"><span class="pre">for</span></tt> loop which follows this pattern.</p>
<p>So looking again at the function definition, the keyword in the header is <tt class="docutils literal"><span class="pre">def</span></tt>, which is
followed by the name of the function and some <em>parameters</em> enclosed in
parentheses. The parameter list may be empty, or it may contain any number of
parameters separated from one another by commas. In either case, the parentheses are required.
The parameters specifies what information, if any, we have to provide in order to use the new function.</p>
<p>Suppose we’re working with turtles, and a common operation we need is to draw
squares. “Draw a square” is an <em>abstraction</em>, or a mental
chunk, of a number of smaller steps. So let’s write a function to capture the pattern
of this “building block”:</p>
<div id="drawsquarefunc" class="pywindow" >
<div id="drawsquarefunc_code_div" style="display: block">
<textarea rows="16" id="drawsquarefunc_code" class="active_code" prefixcode="undefined">
import turtle
def draw_square(t, sz):
"""Make turtle t draw a square of sz."""
for i in range(4):
t.forward(sz)
t.left(90)
wn = turtle.Screen() # Set up the window and its attributes
wn.bgcolor("lightgreen")
wn.title("Alex meets a function")
alex = turtle.Turtle() # Create alex
draw_square(alex, 50) # Call the function to draw the square
wn.mainloop()</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['drawsquarefunc_code'] = true;
pythonTool.readOnlyFlags['drawsquarefunc_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="drawsquarefunc_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="drawsquarefunc_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="drawsquarefunc_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='drawsquarefunc_error'></div>
<div style="text-align: center">
<canvas id="drawsquarefunc_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="drawsquarefunc_suffix" style="display:none">
</pre>
<pre id="drawsquarefunc_pre" class="active_out">
</pre>
<div id="drawsquarefunc_files" class="ac-files ac-files-hidden"></div>
</div>
<p>This function is named <tt class="docutils literal"><span class="pre">draw_square</span></tt>. It has two parameters: one to tell
the function which turtle to move around, and the other to tell it the size
of the square we want drawn. Make sure you know where the body of the function
ends — it depends on the indentation, and the blank lines don’t count for
this purpose!</p>
<div class="admonition-docstrings-for-documentation admonition">
<p class="first admonition-title">Docstrings for documentation</p>
<p>If the first thing after the function header is a string, it is
treated as a <strong>docstring</strong> and gets special treatment in Python and
in some programming tools. For example, when we when we type <tt class="docutils literal"><span class="pre">help('funcname')</span></tt>
in the IDLE shell (where “funcname” is the name of the function), we get a message telling us what arguments the function takes, and it shows
us any other text contained in the docstring. For example, type <tt class="docutils literal"><span class="pre">help('print')</span></tt>
in the IDLE shell and read the message that you get.</p>
<p>Docstrings are the key way to document our functions in Python and
the documentation part is important. Because whoever calls our
function shouldn’t have to need to know what is going on in the
function or how it works; they just need to know what arguments our
function takes, what it does, and what the expected result is.
Enough to be able to use the function without having to look
underneath. This goes back to the concept of abstraction of which
we’ll talk more about.</p>
<p>Docstrings are usually formed using triple-quoted strings as they
allow us to easily expand the docstring later on should we want to
write more than a one-liner.</p>
<p class="last">Just to differentiate from comments, a string at the start of a
function (a docstring) is retrievable by Python tools <em>at runtime</em>.
By contrast, comments are completely eliminated when the program is
parsed.</p>
</div>
<p>Defining a new function does not make the function run. To do that we need a
<strong>function call</strong>. We’ve already seen how to call some built-in functions like
<strong>print</strong>, <strong>range</strong> and <strong>int</strong>. Function calls contain the name of the function being
executed followed by a list of values, called <em>arguments</em>, which are assigned
to the parameters in the function definition. So in line 14 of the program above, we call the function, and pass <tt class="docutils literal"><span class="pre">alex</span></tt> as the turtle to be manipulated,
and 50 as the size of the square we want. While the function is executing, then, the
variable <tt class="docutils literal"><span class="pre">sz</span></tt> refers to the value 50, and the variable <tt class="docutils literal"><span class="pre">t</span></tt> refers to the same
turtle instance that the variable <tt class="docutils literal"><span class="pre">alex</span></tt> refers to.</p>
<p>Once we’ve defined a function, we can call it as often as we like, and its
statements will be executed each time we call it. And we could use it to get
any of our turtles to draw a square. In the next example, we’ve changed the <tt class="docutils literal"><span class="pre">draw_square</span></tt>
function a little, and we get tess to draw 15 squares, with some variations.</p>
<div id="drawmultisquare" class="pywindow" >
<div id="drawmultisquare_code_div" style="display: block">
<textarea rows="23" id="drawmultisquare_code" class="active_code" prefixcode="undefined">
import turtle
def draw_multicolor_square(t, sz):
"""Make turtle t draw a multi-color square of sz."""
for i in ["red", "purple", "hotpink", "blue"]:
t.color(i)
t.forward(sz)
t.left(90)
wn = turtle.Screen() # Set up the window and its attributes
wn.bgcolor("lightgreen")
tess = turtle.Turtle() # Create tess and set some attributes
tess.pensize(3)
size = 20 # Size of the smallest square
for i in range(15):
draw_multicolor_square(tess, size)
size = size + 10 # Increase the size for next time
tess.forward(10) # Move tess along a little
tess.right(18) # and give her some turn
wn.mainloop()</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['drawmultisquare_code'] = true;
pythonTool.readOnlyFlags['drawmultisquare_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="drawmultisquare_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="drawmultisquare_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="drawmultisquare_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='drawmultisquare_error'></div>
<div style="text-align: center">
<canvas id="drawmultisquare_canvas" class="ac-canvas" height="500" width="500" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="drawmultisquare_suffix" style="display:none">
</pre>
<pre id="drawmultisquare_pre" class="active_out">
</pre>
<div id="drawmultisquare_files" class="ac-files ac-files-hidden"></div>
</div>
</div>
<div class="section" id="functions-can-call-other-functions">
<h2>4.2. Functions can call other functions<a class="headerlink" href="#functions-can-call-other-functions" title="Permalink to this headline">¶</a></h2>
<p>Let’s assume now we want a function to draw a rectangle. We need to be able to call
the function with different arguments for width and height. And, unlike the case of the
square, we cannot repeat the same thing 4 times, because the four sides are not equal.</p>
<p>So we eventually come up with this rather nice code that can draw a rectangle.</p>
<div id="rectangleexample" class="pywindow" >
<div id="rectangleexample_code_div" style="display: block">
<textarea rows="7" id="rectangleexample_code" class="active_code" prefixcode="undefined">
def draw_rectangle(t, w, h):
"""Get turtle t to draw a rectangle of width w and height h."""
for i in range(2):
t.forward(w)
t.left(90)
t.forward(h)
t.left(90)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['rectangleexample_code'] = false;
pythonTool.readOnlyFlags['rectangleexample_code'] = true;
</script>
<div id='rectangleexample_error'></div>
<pre id="rectangleexample_suffix" style="display:none">
</pre>
</div>
<p>The parameter names are deliberately chosen as single letters to ensure they’re not misunderstood.
In real programs, once we’ve had more experience, we will insist on better variable names than this.
But the point is that the program doesn’t “understand” that we’re drawing a rectangle, or that the
parameters represent the width and the height. Concepts like rectangle, width, and height are
the meaning we humans have, not concepts that the program or the computer understands.</p>
<p><em>Thinking like a computer scientist</em> involves looking for patterns and
relationships. In the code above, we’ve done that to some extent. We did not just draw four sides.
Instead, we spotted that we could draw the rectangle as two halves, and used a loop to
repeat that pattern twice.</p>
<p>But now we might spot that a square is a special kind of rectangle.
We already have a function that draws a rectangle, so we can use that to draw
our square.</p>
<div id="squareexample" class="pywindow" >
<div id="squareexample_code_div" style="display: block">
<textarea rows="2" id="squareexample_code" class="active_code" prefixcode="undefined">
def draw_square(tx, sz): # A new version of draw_square
draw_rectangle(tx, sz, sz)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['squareexample_code'] = false;
pythonTool.readOnlyFlags['squareexample_code'] = true;
</script>
<div id='squareexample_error'></div>
<pre id="squareexample_suffix" style="display:none">
</pre>
</div>
<p>There are some points worth noting here:</p>
<ul class="simple">
<li>Functions can call other functions.</li>
<li>Rewriting <tt class="docutils literal"><span class="pre">draw_square</span></tt> like this captures the relationship
that we’ve spotted between squares and rectangles.</li>
<li>A caller of this function might say <tt class="docutils literal"><span class="pre">draw_square(tess,</span> <span class="pre">50)</span></tt>. The parameters
of this function, <tt class="docutils literal"><span class="pre">tx</span></tt> and <tt class="docutils literal"><span class="pre">sz</span></tt>, are assigned the values of the tess object, and
the int 50 respectively.</li>
<li>In the body of the function they are just like any other variable.</li>
<li>When the call is made to <tt class="docutils literal"><span class="pre">draw_rectangle</span></tt>, the values in variables <tt class="docutils literal"><span class="pre">tx</span></tt> and <tt class="docutils literal"><span class="pre">sz</span></tt>
are fetched first, then the call happens. So as we enter the top of
function <tt class="docutils literal"><span class="pre">draw_rectangle</span></tt>, its variable <tt class="docutils literal"><span class="pre">t</span></tt> is assigned the tess object, and <tt class="docutils literal"><span class="pre">w</span></tt> and
<tt class="docutils literal"><span class="pre">h</span></tt> in that function are both given the value 50.</li>
</ul>
<p>So far, it may not be clear why it is worth the trouble to create all of these
new functions. Actually, there are a lot of reasons, but this example
demonstrates two:</p>
<ol class="arabic simple">
<li>Creating a new function gives us an opportunity to name a group of
statements. Functions can simplify a program by hiding a complex computation
behind a single command. The function (including its name) can capture our
mental chunking, or <em>abstraction</em>, of the problem.</li>
<li>Creating a new function can make a program smaller by eliminating repetitive
code.</li>
</ol>
<p>As we might expect, we have to create a function before we can execute it.
In other words, the function definition has to be executed before the
function is called.</p>
</div>
<div class="section" id="flow-of-execution">
<span id="index-1"></span><h2>4.3. Flow of execution<a class="headerlink" href="#flow-of-execution" title="Permalink to this headline">¶</a></h2>
<p>In order to ensure that a function is defined before its first use, we have to
know the order in which statements are executed, which is called the <strong>flow of
execution</strong>. We’ve already talked about this a little in the previous chapter.</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 definitions 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. Although it is not common, we can define one function
inside another. In this case, the inner definition isn’t executed until the
outer function is called.</p>
<p>Function calls are like a detour in the flow of execution. Instead of going to
the next statement, the flow jumps to the first line of the called function,
executes all the statements there, and then comes back to pick up where it left
off.</p>
<p>That sounds simple enough, until we 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 adept 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 we read a program, don’t read from
top to bottom. Instead, follow the flow of execution.</p>
</div>
<div class="section" id="functions-that-require-arguments">
<span id="index-2"></span><h2>4.4. Functions that require arguments<a class="headerlink" href="#functions-that-require-arguments" title="Permalink to this headline">¶</a></h2>
<p>Most functions require arguments: the arguments provide for generalization.
For example, if we want to find the absolute value of a number, we have
to indicate what the number is. Python has a built-in function for
computing the absolute value:</p>
<blockquote>
<div><div class="highlight-none"><div class="highlight"><pre>>>> abs(5)
5
>>> abs(-5)
5
</pre></div>
</div>
</div></blockquote>
<p>In this example, the arguments to the <tt class="docutils literal"><span class="pre">abs</span></tt> function are 5 and -5.</p>
<p>Some functions take more than one argument. For example the built-in function
<tt class="docutils literal"><span class="pre">pow</span></tt> takes two arguments, the base and the exponent. Inside the function,
the values that are passed get assigned to variables called <strong>parameters</strong>.</p>
<blockquote>
<div><div class="highlight-none"><div class="highlight"><pre>>>> pow(2, 3)
8
>>> pow(7, 4)
2401
</pre></div>
</div>
</div></blockquote>
<p>Another built-in function that takes more than one argument is <tt class="docutils literal"><span class="pre">max</span></tt>.</p>
<blockquote>
<div><div class="highlight-none"><div class="highlight"><pre>>>> max(7, 11)
11
>>> max(4, 1, 17, 2, 12)
17
>>> max(3 * 11, 5**3, 512 - 9, 1024**0)
503
</pre></div>
</div>
</div></blockquote>
<p><tt class="docutils literal"><span class="pre">max</span></tt> can be passed any number of arguments, separated by commas, and will
return the largest value passed. The arguments can be either simple values or
expressions. In the last example, 503 is returned, since it is larger than 33,
125, and 1.</p>
</div>
<div class="section" id="functions-that-return-values">
<h2>4.5. Functions that return values<a class="headerlink" href="#functions-that-return-values" title="Permalink to this headline">¶</a></h2>
<p>All the functions in the previous section return values.
Furthermore, functions like <tt class="docutils literal"><span class="pre">range</span></tt>, <tt class="docutils literal"><span class="pre">int</span></tt>, <tt class="docutils literal"><span class="pre">abs</span></tt> all return values that
can be used to build more complex expressions.</p>
<p>So an important difference between these functions and one like <tt class="docutils literal"><span class="pre">draw_square</span></tt> is that
<tt class="docutils literal"><span class="pre">draw_square</span></tt> was not executed because we wanted it to compute a value — on the contrary,
we wrote <tt class="docutils literal"><span class="pre">draw_square</span></tt> because we wanted it to execute a sequence of steps that caused
the turtle to draw.</p>
<p>A function that returns a value is called a <strong>fruitful function</strong> in this book.
The opposite of a fruitful function is <strong>void function</strong> — one that is not executed
for its resulting value, but is executed because it does something useful. (Languages
like Java, C#, C and C++ use the term “void function”, other languages like Pascal
call it a <strong>procedure</strong>.) Even though void functions are not executed
for their resulting value, Python always wants to return something. So if the programmer
doesn’t arrange to return a value, Python will automatically return the value <tt class="docutils literal"><span class="pre">None</span></tt>.</p>
<p>How do we write our own fruitful function? Below is
the standard formula for compound interest, which we’ll now write as a fruitful function:</p>
<blockquote>
<div><img alt="_images/compoundInterest.png" src="_images/compoundInterest.png" />
</div></blockquote>
<div id="compoundinterest" class="pywindow" >
<div id="compoundinterest_code_div" style="display: block">
<textarea rows="12" id="compoundinterest_code" class="active_code" prefixcode="undefined">
def final_amt(p, r, n, t):
"""
Apply the compound interest formula to p
to produce the final amount.
"""
a = p * (1 + r/n) ** (n*t)
return a # This is new, and makes the function fruitful.
# now that we have the function above, let us call it.
toInvest = float(input("How much do you want to invest?"))
fnl = final_amt(toInvest, 0.08, 12, 5)
print("At the end of the period you will have " + str(fnl))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['compoundinterest_code'] = true;
pythonTool.readOnlyFlags['compoundinterest_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="compoundinterest_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="compoundinterest_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="compoundinterest_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='compoundinterest_error'></div>
<div style="text-align: center">
<canvas id="compoundinterest_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="compoundinterest_suffix" style="display:none">
</pre>
<pre id="compoundinterest_pre" class="active_out">
</pre>
<div id="compoundinterest_files" class="ac-files ac-files-hidden"></div>
</div>
<ul>
<li><p class="first">The <strong>return</strong> statement is followed an expression (<tt class="docutils literal"><span class="pre">a</span></tt> in this case). This expression will be
evaluated and returned to the caller as the “fruit” of calling this function.</p>
</li>
<li><p class="first">We prompted the user for the principal amount. The type of <tt class="docutils literal"><span class="pre">toInvest</span></tt> is a string, but
we need a number before we can work with it. Because it is money, and could have decimal places,
we’ve used the <tt class="docutils literal"><span class="pre">float</span></tt> type converter function to parse the string and return a float.</p>
</li>
<li><p class="first">Notice how we entered the arguments for 8% interest, compounded 12 times per year, for 5 years.</p>
</li>
<li><p class="first">When we run this, if you use 10000 as your input, you’ll get the output</p>
<blockquote>
<div><p><em>At the end of the period you’ll have 14898.457083</em></p>
</div></blockquote>
<p>This is a bit messy with all these decimal places, but remember that
Python doesn’t understand that we’re working with money: it just does the calculation to
the best of its ability, without rounding.</p>
</li>
<li><p class="first">The line <tt class="docutils literal"><span class="pre">toInvest</span> <span class="pre">=</span> <span class="pre">float(input("How</span> <span class="pre">much</span> <span class="pre">do</span> <span class="pre">you</span> <span class="pre">want</span> <span class="pre">to</span> <span class="pre">invest?"))</span></tt>
also shows yet another example
of <em>composition</em> — we can call a function like <tt class="docutils literal"><span class="pre">float</span></tt>, and its arguments
can be the results of other function calls (like <tt class="docutils literal"><span class="pre">input</span></tt>) that we’ve called along the way.</p>
</li>
</ul>
<p>Notice something else very important here. The name of the variable we pass as an
argument — <tt class="docutils literal"><span class="pre">toInvest</span></tt> — has nothing to do with the name of the parameter
— <tt class="docutils literal"><span class="pre">p</span></tt>. It is as if <tt class="docutils literal"><span class="pre">p</span> <span class="pre">=</span> <span class="pre">toInvest</span></tt> is executed when <tt class="docutils literal"><span class="pre">final_amt</span></tt> is called.
It doesn’t matter what the value was named in
the caller, in <tt class="docutils literal"><span class="pre">final_amt</span></tt> its name is <tt class="docutils literal"><span class="pre">p</span></tt>.</p>
<p>These short variable names are getting quite tricky, so perhaps we’d prefer one of these
versions instead:</p>
<div id="finalamtimproves" class="pywindow" >
<div id="finalamtimproves_code_div" style="display: block">
<textarea rows="9" id="finalamtimproves_code" class="active_code" prefixcode="undefined">
def final_amt_v2(principalAmount, nominalPercentageRate,
numTimesPerYear, years):
a = principalAmount * (1 + nominalPercentageRate /
numTimesPerYear) ** (numTimesPerYear*years)
return a
def final_amt_v3(amt, rate, compounded, years):
a = amt * (1 + rate/compounded) ** (componded*years)
return a</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['finalamtimproves_code'] = false;
pythonTool.readOnlyFlags['finalamtimproves_code'] = true;
</script>
<div id='finalamtimproves_error'></div>
<pre id="finalamtimproves_suffix" style="display:none">
</pre>
</div>
<p>They all do the same thing. Use your judgement to write code that can be best
understood by other humans!
Short variable names are more economical and sometimes make
code easier to read:
E = mc<sup>2</sup> would not be nearly so memorable if Einstein had
used longer variable names! If you do prefer short names,
make sure you also have some comments to enlighten the reader
about what the variables are used for.</p>
</div>
<div class="section" id="variables-and-parameters-are-local">
<span id="index-3"></span><h2>4.6. Variables and parameters are local<a class="headerlink" href="#variables-and-parameters-are-local" title="Permalink to this headline">¶</a></h2>
<p>When we create a <strong>local variable</strong> inside a function, it only exists inside
the function, and we cannot use it outside. For example, consider again this function:</p>
<div id="localvarexample" class="pywindow" >
<div id="localvarexample_code_div" style="display: block">
<textarea rows="3" id="localvarexample_code" class="active_code" prefixcode="undefined">
def final_amt(p, r, n, t):
a = p * (1 + r/n) ** (n*t)
return a</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['localvarexample_code'] = false;
pythonTool.readOnlyFlags['localvarexample_code'] = true;
</script>
<div id='localvarexample_error'></div>
<pre id="localvarexample_suffix" style="display:none">
</pre>
</div>
<p>If we try to use <tt class="docutils literal"><span class="pre">a</span></tt>, outside the function, we’ll get an error:</p>
<blockquote>
<div><div class="highlight-none"><div class="highlight"><pre>Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a
NameError: name 'a' is not defined
</pre></div>
</div>
</div></blockquote>
<p>The variable <tt class="docutils literal"><span class="pre">a</span></tt> is local to <tt class="docutils literal"><span class="pre">final_amt</span></tt>, and is not visible
outside the function.</p>
<p>Additionally, <tt class="docutils literal"><span class="pre">a</span></tt> only exists while the function is being executed —
we call this its <strong>lifetime</strong>.
When the execution of the function terminates,
the local variables are destroyed.</p>
<p>Parameters are also local, and act like local variables.
For example, the lifetimes of <tt class="docutils literal"><span class="pre">p</span></tt>, <tt class="docutils literal"><span class="pre">r</span></tt>, <tt class="docutils literal"><span class="pre">n</span></tt>, <tt class="docutils literal"><span class="pre">t</span></tt> begin when <tt class="docutils literal"><span class="pre">final_amt</span></tt> is called,
and the lifetime ends when the function completes its execution.</p>
<p>So it is not possible for a function to set some local variable to a
value, complete its execution, and then when it is called again next
time, recover the local variable. Each call of the function creates
new local variables, and their lifetimes expire when the function returns
to the caller.</p>
</div>
<div class="section" id="turtles-revisited">
<span id="index-4"></span><h2>4.7. Turtles Revisited<a class="headerlink" href="#turtles-revisited" title="Permalink to this headline">¶</a></h2>
<p>Now that we have fruitful functions, we can focus our attention on
reorganizing our code so that it fits more nicely into our mental chunks.
This process of rearrangement is called <strong>refactoring</strong> the code.</p>
<p>Two things we’re always going to want to do when working with turtles
is to create the window for the turtle, and to create one or more turtles.
For example, we could write some functions to make these tasks easier in future:</p>
<div id="turtlechunks" class="pywindow" >
<div id="turtlechunks_code_div" style="display: block">
<textarea rows="20" id="turtlechunks_code" class="active_code" prefixcode="undefined">
def make_window(colr, ttle):
"""
Set up the window with the given background color and title.
Returns the new window.
"""
w = turtle.Screen()
w.bgcolor(colr)
w.title(ttle)
return w
def make_turtle(colr, sz):
"""
Set up a turtle with the given color and pensize.
Returns the new turtle.
"""
t = turtle.Turtle()
t.color(colr)
t.pensize(sz)
return t</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['turtlechunks_code'] = false;
pythonTool.readOnlyFlags['turtlechunks_code'] = true;
</script>
<div id='turtlechunks_error'></div>
<pre id="turtlechunks_suffix" style="display:none">
</pre>
</div>
<p>Then we could make new turtles easily, like so:</p>
<div id="turtlecreates" class="pywindow" >
<div id="turtlecreates_code_div" style="display: block">
<textarea rows="4" id="turtlecreates_code" class="active_code" prefixcode="undefined">
wn = make_window("lightgreen", "Tess and Alex dancing")
tess = make_turtle("hotpink", 5)
alex = make_turtle("black", 1)
dave = make_turtle("yellow", 2)</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['turtlecreates_code'] = false;
pythonTool.readOnlyFlags['turtlecreates_code'] = true;
</script>
<div id='turtlecreates_error'></div>
<pre id="turtlecreates_suffix" style="display:none">
</pre>
</div>
<p>The trick about refactoring code is to anticipate which things we are likely to want to change
each time we call the function: these should become the parameters, or changeable parts,
of the functions we write.</p>
<span class="target" id="index-5"></span></div>
<div class="section" id="return-values">
<span id="index-6"></span><h2>4.8. Return values<a class="headerlink" href="#return-values" title="Permalink to this headline">¶</a></h2>
<p>The built-in functions we have used, such as <tt class="docutils literal"><span class="pre">abs</span></tt>, <tt class="docutils literal"><span class="pre">pow</span></tt>, <tt class="docutils literal"><span class="pre">int</span></tt>, <tt class="docutils literal"><span class="pre">max</span></tt>, and <tt class="docutils literal"><span class="pre">range</span></tt>,
have produced results. Calling each of these functions generates a value, which
we usually assign to a variable or use as part of an expression.</p>
<div id="buildinfuncsex" class="pywindow" >
<div id="buildinfuncsex_code_div" style="display: block">
<textarea rows="2" id="buildinfuncsex_code" class="active_code" prefixcode="undefined">
biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['buildinfuncsex_code'] = false;
pythonTool.readOnlyFlags['buildinfuncsex_code'] = true;
</script>
<div id='buildinfuncsex_error'></div>
<pre id="buildinfuncsex_suffix" style="display:none">
</pre>
</div>
<p>We also wrote our own function to return the final amount for a compound interest calculation.</p>
<p>We are going to write more functions that return values, which we
will call <em>fruitful functions</em>, for want of a better name. The first example
is <tt class="docutils literal"><span class="pre">area</span></tt>, which returns the area of a circle with the given radius:</p>
<div id="areaofcircle" class="pywindow" >
<div id="areaofcircle_code_div" style="display: block">
<textarea rows="3" id="areaofcircle_code" class="active_code" prefixcode="undefined">
def area(radius):
b = 3.14159 * radius**2
return b</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['areaofcircle_code'] = false;
pythonTool.readOnlyFlags['areaofcircle_code'] = true;
</script>
<div id='areaofcircle_error'></div>
<pre id="areaofcircle_suffix" style="display:none">
</pre>
</div>
<p>We have seen the <tt class="docutils literal"><span class="pre">return</span></tt> statement before: in a fruitful function the
<tt class="docutils literal"><span class="pre">return</span></tt> statement includes a <strong>return value</strong>. This statement means: evaluate
the return expression, and then return it immediately as the result (the fruit)
of this function. The expression provided can be arbitrarily complicated,
so we could have written this function like this:</p>
<div id="areaofcircle2" class="pywindow" >
<div id="areaofcircle2_code_div" style="display: block">
<textarea rows="2" id="areaofcircle2_code" class="active_code" prefixcode="undefined">
def area(radius):
return 3.14159 * radius * radius</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['areaofcircle2_code'] = false;
pythonTool.readOnlyFlags['areaofcircle2_code'] = true;
</script>
<div id='areaofcircle2_error'></div>
<pre id="areaofcircle2_suffix" style="display:none">
</pre>
</div>
<p>On the other hand, <strong>temporary variables</strong> like <tt class="docutils literal"><span class="pre">b</span></tt> above often make debugging
easier.</p>
</div>
<div class="section" id="program-development">
<span id="index-7"></span><h2>4.9. Program development<a class="headerlink" href="#program-development" title="Permalink to this headline">¶</a></h2>
<p>At this point, you should be able to look at complete functions and tell what
they do. Also, you have already written some
small functions. As you write larger functions, you might start to have more
difficulty, especially with runtime and semantic errors.</p>
<p>To deal with increasingly complex programs, we are going to suggest a technique
called <strong>incremental development</strong>. The goal of incremental development is to
avoid long debugging sessions by adding and testing only a small amount of code
at a time.</p>
<p>As an example, suppose we want to find the distance between two points, given
by the coordinates (x<sub>1</sub>, y<sub>1</sub>) and
(x<sub>2</sub>, y<sub>2</sub>). By the Pythagorean theorem, the distance is:</p>
<blockquote>
<div><img alt="Distance formula" src="_images/distance_formula.png" />
</div></blockquote>
<p>Don’t worry if you don’t know this formula or how to prove it. We’re just going to worry about how to implement it in Python.</p>
<p>The first step is to consider what a <tt class="docutils literal"><span class="pre">distance</span></tt> function should look like in
Python. In other words, what are the inputs (parameters) and what is the output
(return value)?</p>
<p>In this case, the two points are the inputs, which we can represent using four
parameters. The return value is the distance, which is a floating-point value.</p>
<p>Already we can write an outline of the function that captures our thinking so far:</p>
<div id="distancepart1a" class="pywindow" >
<div id="distancepart1a_code_div" style="display: block">
<textarea rows="2" id="distancepart1a_code" class="active_code" prefixcode="undefined">
def distance(x1, y1, x2, y2):
return 0.0</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['distancepart1a_code'] = true;
pythonTool.readOnlyFlags['distancepart1a_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="distancepart1a_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="distancepart1a_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="distancepart1a_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='distancepart1a_error'></div>
<div style="text-align: center">
<canvas id="distancepart1a_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="distancepart1a_suffix" style="display:none">
</pre>
<pre id="distancepart1a_pre" class="active_out">
</pre>
<div id="distancepart1a_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Obviously, this version of the function doesn’t compute distances; it always
returns zero. But it is syntactically correct, and it will run, which means
that we can test it before we make it more complicated.</p>
<p>To test the new function, we call it with sample values:</p>
<div id="distancepart1b" class="pywindow" >
<div id="distancepart1b_code_div" style="display: block">
<textarea rows="4" id="distancepart1b_code" class="active_code" prefixcode="undefined">
def distance(x1, y1, x2, y2):
return 0.0
print(distance(1,2,4,6))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['distancepart1b_code'] = true;
pythonTool.readOnlyFlags['distancepart1b_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="distancepart1b_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="distancepart1b_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="distancepart1b_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='distancepart1b_error'></div>
<div style="text-align: center">
<canvas id="distancepart1b_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="distancepart1b_suffix" style="display:none">
</pre>
<pre id="distancepart1b_pre" class="active_out">
</pre>
<div id="distancepart1b_files" class="ac-files ac-files-hidden"></div>
</div>
<p>We chose these values so that the horizontal distance equals 3 and the vertical
distance equals 4; that way, the result is 5 (the hypotenuse of a 3-4-5
triangle). When testing a function, it is useful to know the right answer.</p>
<p>At this point we have confirmed that the function is syntactically correct, and
we can start adding lines of code. After each incremental change, we test the
function again. If an error occurs at any point, we know where it must be — in
the last line we added.</p>
<p>A logical first step in the computation is to find the differences
x<sub>2</sub>- x<sub>1</sub> and y<sub>2</sub>- y<sub>1</sub>. We will
refer to those values using temporary variables named <tt class="docutils literal"><span class="pre">dx</span></tt> and <tt class="docutils literal"><span class="pre">dy</span></tt>.</p>
<div id="distancepart2a" class="pywindow" >
<div id="distancepart2a_code_div" style="display: block">
<textarea rows="6" id="distancepart2a_code" class="active_code" prefixcode="undefined">
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return 0.0
print(distance(1,2,4,6))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['distancepart2a_code'] = true;
pythonTool.readOnlyFlags['distancepart2a_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="distancepart2a_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="distancepart2a_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="distancepart2a_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='distancepart2a_error'></div>
<div style="text-align: center">
<canvas id="distancepart2a_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="distancepart2a_suffix" style="display:none">
</pre>
<pre id="distancepart2a_pre" class="active_out">
</pre>
<div id="distancepart2a_files" class="ac-files ac-files-hidden"></div>
</div>
<p>If we call the function with the arguments shown above, when the flow of execution
gets to the return statement, <tt class="docutils literal"><span class="pre">dx</span></tt> should be 3 and <tt class="docutils literal"><span class="pre">dy</span></tt> should be 4.
We can check that this is the case by putting in temporary <tt class="docutils literal"><span class="pre">print</span></tt> statements in the function, like so:</p>
<div id="distancepart2b" class="pywindow" >
<div id="distancepart2b_code_div" style="display: block">
<textarea rows="8" id="distancepart2b_code" class="active_code" prefixcode="undefined">
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
print("dx = "+str(dx))
print("dy = "+str(dy))
return 0.0
print(distance(1,2,4,6))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['distancepart2b_code'] = true;
pythonTool.readOnlyFlags['distancepart2b_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="distancepart2b_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="distancepart2b_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="distancepart2b_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='distancepart2b_error'></div>
<div style="text-align: center">
<canvas id="distancepart2b_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="distancepart2b_suffix" style="display:none">
</pre>
<pre id="distancepart2b_pre" class="active_out">
</pre>
<div id="distancepart2b_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Now we can confirm that the function is getting the right parameters and performing the first
computation correctly. If not, there are only a few lines to check. Once we’re sure that
<tt class="docutils literal"><span class="pre">dx</span></tt> and <tt class="docutils literal"><span class="pre">dy</span></tt> are working correctly, we should remove the temporary <tt class="docutils literal"><span class="pre">print</span></tt> statements — we don’t want them in our final program.</p>
<p>Next we compute the sum of squares of <tt class="docutils literal"><span class="pre">dx</span></tt> and <tt class="docutils literal"><span class="pre">dy</span></tt>:</p>
<div id="distancepart3a" class="pywindow" >
<div id="distancepart3a_code_div" style="display: block">
<textarea rows="7" id="distancepart3a_code" class="active_code" prefixcode="undefined">
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx*dx + dy*dy
return 0.0
print(distance(1,2,4,6))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['distancepart3a_code'] = true;
pythonTool.readOnlyFlags['distancepart3a_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="distancepart3a_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="distancepart3a_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="distancepart3a_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='distancepart3a_error'></div>
<div style="text-align: center">
<canvas id="distancepart3a_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>
</div>
<pre id="distancepart3a_suffix" style="display:none">
</pre>
<pre id="distancepart3a_pre" class="active_out">
</pre>
<div id="distancepart3a_files" class="ac-files ac-files-hidden"></div>
</div>
<p>Again, we could put in a temporary <tt class="docutils literal"><span class="pre">print</span></tt> statement, then run the program at this stage and check the value of <tt class="docutils literal"><span class="pre">dsquared</span></tt> (which
should be 25):</p>
<div id="distancepart3b" class="pywindow" >
<div id="distancepart3b_code_div" style="display: block">
<textarea rows="8" id="distancepart3b_code" class="active_code" prefixcode="undefined">
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx*dx + dy*dy
print("dsquared = "+str(dsquared))
return 0.0
print(distance(1,2,4,6))</textarea>
</div>
<script type="text/javascript">
pythonTool.lineNumberFlags['distancepart3b_code'] = true;
pythonTool.readOnlyFlags['distancepart3b_code'] = false;
</script>
<div>
<button style="float:left" type='button' class='btn btn-run' id="distancepart3b_runb">Run</button>
<button style="float:left; margin-left:150px;" type='button' class='btn' id="distancepart3b_popb">Pop Out</button>
<button style="float:right" type="button" class='btn btn-reset' id="distancepart3b_resetb">Reset</button>
<div style='clear:both'></div>
</div>
<div id='distancepart3b_error'></div>