Repository navigation
Expand file tree
/
Copy pathFunctions.html
More file actions
290 lines (248 loc) · 25.2 KB
/
Copy pathFunctions.html
File metadata and controls
290 lines (248 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<!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>Functions — PythonCert 4.0 documentation</title>
<link rel="stylesheet" href="../_static/alabaster.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '4.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</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="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="IPython Introduction" href="../modules/IPythonIntroduction.html" />
<link rel="prev" title="Functional Programming" href="FunctionalProgramming.html" />
<link rel="stylesheet" href="../_static/custom.css" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
</head>
<body>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="functions">
<h1>Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h1>
<div class="section" id="with-rick-riehle">
<h2>With Rick Riehle<a class="headerlink" href="#with-rick-riehle" title="Permalink to this headline">¶</a></h2>
<p>We have seen some of the building blocks of programs such as basic data structures, conditional flow control statements like <code class="docutils literal"><span class="pre">if</span></code> and looping constructs such as <code class="docutils literal"><span class="pre">while</span></code> and <code class="docutils literal"><span class="pre">for</span></code>. We can do quite a lot with these constructs alone.</p>
<p>Take a moment to think about what your programs will look like using only these constructs. If you are relatively new to programming this should be easy. If you’ve been around for awhile, you may need to forget some of what you already know for this thought experiment to work.</p>
<p>Using only the basic building blocks you start at the top of your program and work your way to the bottom. You likely define a few variables early on. From there you might have an <code class="docutils literal"><span class="pre">if</span></code> statement that conditionally executes some code block rather than some other code block. Beyond that perhaps you iterate over a list with a <code class="docutils literal"><span class="pre">for</span></code> loop. Maybe you load data from a database into a list of tuples and iterate over those, printing to the console the interesting bits. At the end it might be nice to print ‘Done!’</p>
<p>Think about this in its general form. Where does execution begin and where does it end? What happens if you find yourself repeating the same code, the same series of statements, in several <code class="docutils literal"><span class="pre">while</span></code> or <code class="docutils literal"><span class="pre">for</span></code> loops. What happens if you need to change the code in one of the loops, say in response to a change in the fields returned from your database, yet forget to change the corresponding code in all of the loops?</p>
<p>Without a higher level construct to help organize our code it will be closer to a script than a program. Scripts are common in the automation of systems-level tasks, the type of programming used regularly by Systems Administrators and Devops Developers. To move beyond scripts we need functions.</p>
</div>
<div class="section" id="basic-function-definition">
<h2>Basic Function Definition<a class="headerlink" href="#basic-function-definition" title="Permalink to this headline">¶</a></h2>
<p>The basic form of a function is a <code class="docutils literal"><span class="pre">def</span></code> statement, followed by the name of the function <code class="docutils literal"><span class="pre">addOne</span></code> followed by an argument list <code class="docutils literal"><span class="pre">(x)</span></code> and finally a colon, <code class="docutils literal"><span class="pre">:</span></code>. All of this is typically on the first line of the function definition. Then within the function are all of the statements and expressions that do the work of the function <code class="docutils literal"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">x</span> <span class="pre">+</span> <span class="pre">1</span></code> and finally a return value <code class="docutils literal"><span class="pre">return</span> <span class="pre">result</span></code>.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">addOne</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span>
<span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>In simple cases such as this all of the work of the function can be done on the return line which eliminates a name <code class="docutils literal"><span class="pre">result</span></code> and makes the function easier to read.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">addOne</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span>
</pre></div>
</div>
</div>
<div class="section" id="arguments">
<h2>Arguments<a class="headerlink" href="#arguments" title="Permalink to this headline">¶</a></h2>
<p>Functions can take more than a single argument.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="o">+</span> <span class="n">z</span>
</pre></div>
</div>
<p>Functions can have default values for arguments so that the caller can neglect to specify certain arguments and yet get reasonable defaults.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="gp">In [12]: </span><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">z</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
<span class="go"> ...: return x + y + z</span>
<span class="go"> ...:</span>
<span class="gp">In [13]: </span><span class="n">add</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gh">Out[13]: </span><span class="go">3</span>
<span class="gp">In [14]: </span><span class="n">add</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="gh">Out[14]: </span><span class="go">5</span>
<span class="gp">In [15]: </span><span class="n">add</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="gh">Out[15]: </span><span class="go">6</span>
</pre></div>
</div>
<p>We snuck in an interesting and useful feature of functions in Python: keyword arguments which are often called kwargs for short. The second and third arguments to our function above have names. The first named or keyword argument is <code class="docutils literal"><span class="pre">y</span></code> and the second is <code class="docutils literal"><span class="pre">z</span></code>. Note that the act itself of giving default values to arguments turns them from standard positional arguments into keyword arguments. This allows the caller to specify them by name rather than by position so that they can be called in any order. For instance, <code class="docutils literal"><span class="pre">z</span></code> can be specified before <code class="docutils literal"><span class="pre">y</span></code>.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="gp">In [16]: </span><span class="n">add</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">z</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gh">Out[16]: </span><span class="go">3</span>
</pre></div>
</div>
<p>Kwargs also allow the caller to skip unneeded arguments and rely instead on their defaults.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="gp">In [17]: </span><span class="n">add</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">z</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gh">Out[17]: </span><span class="go">1</span>
</pre></div>
</div>
<p>Note however, that positional arguments cannot be skipped. In this simple case we have only one positional argument <code class="docutils literal"><span class="pre">x</span></code> which Python will not permit us to ignore.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="gp">In [18]: </span><span class="n">add</span><span class="p">(</span><span class="n">y</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">z</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="gt">-------------------------------------------------------------------------------</span>
<span class="ne">TypeError</span><span class="g g-Whitespace"> </span>Traceback (most recent call last)
<span class="nn"><ipython-input-18-5b53a9942d6b></span> in <span class="ni"><module></span><span class="nt">()</span>
<span class="ne">----> </span><span class="mi">1</span> <span class="n">add</span><span class="p">(</span><span class="n">y</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">z</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="ne">TypeError</span>: add() missing 1 required positional argument: 'x'
</pre></div>
</div>
</div>
<div class="section" id="return-values">
<h2>Return Values<a class="headerlink" href="#return-values" title="Permalink to this headline">¶</a></h2>
<p>Functions can also take zero arguments and return nothing. Simply leave off the return statement and your function will return no value, or <code class="docutils literal"><span class="pre">None</span></code>, to its caller.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">sayHello</span><span class="p">():</span>
<span class="k">print</span><span class="p">(</span><span class="s2">"Hello"</span><span class="p">)</span>
</pre></div>
</div>
<p>Interestingly, in Python functions can return more than a single value. They can return two, three, four, or indeed an arbitrary number of values. Simply place commas between the values you plan to return.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="gp">In [1]: </span><span class="k">def</span> <span class="nf">giveMeTwoValues</span><span class="p">():</span>
<span class="go"> ...: return 1, "two"</span>
<span class="go"> ...:</span>
<span class="gp">In [2]: </span><span class="n">first</span><span class="p">,</span> <span class="n">second</span> <span class="o">=</span> <span class="n">giveMeTwoValues</span><span class="p">()</span>
<span class="gp">In [3]: </span><span class="n">first</span>
<span class="gh">Out[3]: </span><span class="go">1</span>
<span class="gp">In [4]: </span><span class="n">second</span>
<span class="gh">Out[4]: </span><span class="go">'two'</span>
</pre></div>
</div>
<p>Give the return value a single name and the objects will be packed into a tuple; each object in the tuple can be accessed according to its position.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="gp">In [25]: </span><span class="n">myTwoValues</span> <span class="o">=</span> <span class="n">giveMeTwoValues</span><span class="p">()</span>
<span class="gp">In [26]: </span><span class="n">myTwoValues</span>
<span class="gh">Out[26]: </span><span class="go">(1, 'two')</span>
<span class="gp">In [27]: </span><span class="nb">type</span><span class="p">(</span><span class="n">myTwoValues</span><span class="p">)</span>
<span class="gh">Out[27]: </span><span class="go">tuple</span>
<span class="gp">In [28]: </span><span class="n">myTwoValues</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gh">Out[28]: </span><span class="go">1</span>
<span class="gp">In [29]: </span><span class="n">myTwoValues</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="gh">Out[29]: </span><span class="go">'two'</span>
<span class="gp">In [30]: </span><span class="nb">type</span><span class="p">(</span><span class="n">myTwoValues</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="gh">Out[30]: </span><span class="go">int</span>
<span class="gp">In [31]: </span><span class="nb">type</span><span class="p">(</span><span class="n">myTwoValues</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="gh">Out[31]: </span><span class="go">str</span>
</pre></div>
</div>
</div>
<div class="section" id="scope">
<h2>Scope<a class="headerlink" href="#scope" title="Permalink to this headline">¶</a></h2>
<p>Functions can carry variables that come into existence and go out of existence during the run of the function. This is known as scope. I could have as correctly said that these variables come into scope and go out of scope during the run of the function.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="gp">In [1]: </span><span class="k">def</span> <span class="nf">my_func</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">1</span><span class="p">):</span>
<span class="gp"> ...: </span> <span class="n">a</span> <span class="o">=</span> <span class="s2">"alpha"</span>
<span class="gp"> ...: </span> <span class="n">b</span> <span class="o">=</span> <span class="s2">"beta"</span>
<span class="gp"> ...: </span> <span class="k">return</span> <span class="n">a</span><span class="o">*</span><span class="n">x</span><span class="p">,</span> <span class="n">b</span><span class="o">*</span><span class="n">x</span>
<span class="gp"> ...:</span>
<span class="gp">In [2]: </span><span class="n">my_func</span><span class="p">()</span>
<span class="gh">Out[2]: </span><span class="go">('alpha', 'beta')</span>
<span class="gp">In [3]: </span><span class="n">my_func</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="gh">Out[3]: </span><span class="go">('alphaalpha', 'betabeta')</span>
</pre></div>
</div>
<p>Variables that are defined within a function are called local variables, because they are local to the function. Note that once the function has completed executing its local variables are no longer in scope.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="gp">In [4]: </span><span class="n">a</span>
<span class="gt">---------------------------------------------------------------------------</span>
<span class="ne">NameError</span><span class="g g-Whitespace"> </span>Traceback (most recent call last)
<span class="nn"><ipython-input-4-3f786850e387></span> in <span class="ni"><module></span><span class="nt">()</span>
<span class="ne">----> </span><span class="mi">1</span> <span class="n">a</span>
<span class="ne">NameError</span>: name 'a' is not defined
<span class="gp">In [5]: </span><span class="n">b</span>
<span class="gt">---------------------------------------------------------------------------</span>
<span class="ne">NameError</span><span class="g g-Whitespace"> </span>Traceback (most recent call last)
<span class="nn"><ipython-input-5-89e6c98d9288></span> in <span class="ni"><module></span><span class="nt">()</span>
<span class="ne">----> </span><span class="mi">1</span> <span class="n">b</span>
<span class="ne">NameError</span>: name 'b' is not defined
</pre></div>
</div>
<p>Python’s scoping rules are such that any variables outside the function with the same names are masked by local variables. In other words, if <code class="docutils literal"><span class="pre">a</span></code> and <code class="docutils literal"><span class="pre">b</span></code> are defined outside the function they do not interfere with the variables inside the function.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="gp">In [6]: </span><span class="n">a</span> <span class="o">=</span> <span class="s2">"apple"</span>
<span class="gp">In [7]: </span><span class="n">b</span> <span class="o">=</span> <span class="s2">"banana"</span>
<span class="gp">In [8]: </span><span class="n">my_func</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="gh">Out[8]: </span><span class="go">('alphaalpha', 'betabeta')</span>
</pre></div>
</div>
<p><code class="docutils literal"><span class="pre">my_func</span></code> still returns alphas and betas rather than apples and bananas.</p>
<p>While we are still on the topic of scope and which names are available when, let’s take the example above and put it into an executable python file or a script.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">my_func</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">1</span><span class="p">):</span>
<span class="n">a</span> <span class="o">=</span> <span class="s2">"alpha"</span>
<span class="n">b</span> <span class="o">=</span> <span class="s2">"beta"</span>
<span class="k">return</span> <span class="n">a</span><span class="o">*</span><span class="n">x</span><span class="p">,</span> <span class="n">b</span><span class="o">*</span><span class="n">x</span>
<span class="n">a</span> <span class="o">=</span> <span class="s2">"apple"</span>
<span class="n">b</span> <span class="o">=</span> <span class="s2">"banana"</span>
</pre></div>
</div>
<p>Look at the sturcutre of that code, it’s physical layout. Notice how certain elements are indented under others. Notice that some are not indented at all, but rather sit along the left margin of the file. This is meaningful. The indented elements are only in scope within their enclosing blocks. Python is very explicit about this: indentation is meaningful. When Python was first created this was on of its most controversial features. Other languages used syntactic elements such as parenthesis, brackets and semi-colons to indicate structure including things like scope. Python dispensed with most of that and some people like it and some people don’t. The purpose is so that as programmers, at a glance, we have clear visual clues as to what is related to what. Clues at to which symbols are in scope and when. Python also has a rigorous style guide called PEP8 which we will refer to regularly during the class. Other languages also recognize how useful these visual clues can be and so now most code editors have auto-formatting features which follow conventions, conventions like PEP8, about how code should be laid out for whatever language you happen to be working in. One nice effect of all this is that as you spend more and more time with the language the details of its syntax tends to fade into the background which allows you as the programmer to pay more attention to the problem you are trying to solve. Just as with a written language such as English or Spanish: after awhile you hardly see the syntax and you focus on the words and their meaning. The conventions around paragraph indentation give you clues about where one idea ends and another begins. So it is with computer code, particularly Python.</p>
<p>Python3 has two keywords for controlling scope: <code class="docutils literal"><span class="pre">global</span></code> and <code class="docutils literal"><span class="pre">nonlocal</span></code>. In a sense they are for breaking the scoping rules and conventions we’ve talked about. Don’t worry about them for now. Know they’re there, and know that you can use them as a lazy way to get out of a tight spot. We will probably talk about them down the road, perhaps when we start defining functions within functions.</p>
</div>
<div class="section" id="summary">
<h2>Summary<a class="headerlink" href="#summary" title="Permalink to this headline">¶</a></h2>
<p>Now think back to our thought experiment from when we started. How could the use of functions improve the way we construct programs? Perhaps most significantly we can now reduce code redundancy by factoring out repetitive code blocks as functions which can be called from wherever in our program they are needed. Moreover Where once we had to work strictly from the top of our program to the bottom we can now construct a series of functions that can be called from a main routine or from higher level functions making our program more readable.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">Functions</a><ul>
<li><a class="reference internal" href="#with-rick-riehle">With Rick Riehle</a></li>
<li><a class="reference internal" href="#basic-function-definition">Basic Function Definition</a></li>
<li><a class="reference internal" href="#arguments">Arguments</a></li>
<li><a class="reference internal" href="#return-values">Return Values</a></li>
<li><a class="reference internal" href="#scope">Scope</a></li>
<li><a class="reference internal" href="#summary">Summary</a></li>
</ul>
</li>
</ul>
<div class="relations">
<h3>Related Topics</h3>
<ul>
<li><a href="../index.html">Documentation overview</a><ul>
<li>Previous: <a href="FunctionalProgramming.html" title="previous chapter">Functional Programming</a></li>
<li>Next: <a href="../modules/IPythonIntroduction.html" title="next chapter">IPython Introduction</a></li>
</ul></li>
</ul>
</div>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/scripts/Functions.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
©2017, Christopher Barker, Cris Ewing, Christy Heaton, Maria McKinley, Rick Riehle, Joseph Schilz.
|
Powered by <a href="http://sphinx-doc.org/">Sphinx 1.6.2</a>
& <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a>
|
<a href="../_sources/scripts/Functions.rst.txt"
rel="nofollow">Page source</a>
</div>
</body>
</html>