forked from swcarpentry/python-novice-inflammation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06-func.html
436 lines (407 loc) · 35.3 KB
/
06-func.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<title>Software Carpentry: Programming with Python</title>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
<link rel="stylesheet" type="text/css" href="css/swc.css" />
<link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
<meta charset="UTF-8" />
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body class="lesson">
<div class="container card">
<div class="banner">
<a href="http://software-carpentry.org" title="Software Carpentry">
<img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
</a>
</div>
<article>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<a href="index.html"><h1 class="title">Programming with Python</h1></a>
<h2 class="subtitle">Creating Functions</h2>
<section class="objectives panel panel-warning">
<div class="panel-heading">
<h2 id="learning-objectives"><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Define a function that takes parameters.</li>
<li>Return a value from a function.</li>
<li>Test and debug a function.</li>
<li>Set default values for function parameters.</li>
<li>Explain why we should divide programs into small, single-purpose functions.</li>
</ul>
</div>
</section>
<p>At this point, we’ve written code to draw some interesting features in our inflammation data, loop over all our data files to quickly draw these plots for each of them, and have Python make decisions based on what it sees in our data. But, our code is getting pretty long and complicated; what if we had thousands of datasets, and didn’t want to generate a figure for every single one? Commenting out the figure-drawing code is a nuisance. Also, what if we want to use that code again, on a different dataset or at a different point in our program? Cutting and pasting it is going to make our code get very long and very repetitive, very quickly. We’d like a way to package our code so that it is easier to reuse, and Python provides for this by letting us define things called ‘functions’ - a shorthand way of re-executing longer pieces of code.</p>
<p>Let’s start by defining a function <code>fahr_to_kelvin</code> that converts temperatures from Fahrenheit to Kelvin:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> fahr_to_kelvin(temp):
<span class="cf">return</span> ((temp <span class="op">-</span> <span class="dv">32</span>) <span class="op">*</span> (<span class="dv">5</span><span class="op">/</span><span class="dv">9</span>)) <span class="op">+</span> <span class="fl">273.15</span></code></pre></div>
<p>The function definition opens with the word <code>def</code>, which is followed by the name of the function and a parenthesized list of parameter names. The <a href="reference.html#function-body">body</a> of the function — the statements that are executed when it runs — is indented below the definition line.</p>
<p>When we call the function, the values we pass to it are assigned to those variables so that we can use them inside the function. Inside the function, we use a <a href="reference.html#return-statement">return statement</a> to send a result back to whoever asked for it.</p>
<p>Let’s try running our function. Calling our own function is no different from calling any other function:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">'freezing point of water:'</span>, fahr_to_kelvin(<span class="dv">32</span>))
<span class="bu">print</span>(<span class="st">'boiling point of water:'</span>, fahr_to_kelvin(<span class="dv">212</span>))</code></pre></div>
<pre class="output"><code>freezing point of water: 273.15
boiling point of water: 373.15</code></pre>
<p>We’ve successfully called the function that we defined, and we have access to the value that we returned.</p>
<aside class="callout panel panel-info">
<div class="panel-heading">
<h2 id="integer-division"><span class="glyphicon glyphicon-pushpin"></span>Integer division</h2>
</div>
<div class="panel-body">
<p>We are using Python 3, where division always returns a floating point number:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">$ python3 <span class="op">-</span>c <span class="st">"print(5/9)"</span></code></pre></div>
<pre class="output"><code>0.5555555555555556</code></pre>
<p>Unfortunately, this wasn’t the case in Python 2:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">5</span><span class="op">/</span><span class="dv">9</span></code></pre></div>
<pre class="output"><code>0</code></pre>
<p>If you are using Python 2 and want to keep the fractional part of division you need to convert one or the other number to floating point:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">float</span>(<span class="dv">5</span>)<span class="op">/</span><span class="dv">9</span></code></pre></div>
<pre class="output"><code>0.555555555556</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">5</span><span class="op">/</span><span class="bu">float</span>(<span class="dv">9</span>)</code></pre></div>
<pre class="output"><code>0.555555555556</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="fl">5.0</span><span class="op">/</span><span class="dv">9</span></code></pre></div>
<pre class="output"><code>0.555555555556</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">5</span><span class="op">/</span><span class="fl">9.0</span></code></pre></div>
<pre class="output"><code>0.555555555556</code></pre>
<p>And if you want an integer result from division in Python 3, use a double-slash:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">4</span><span class="op">//</span><span class="dv">2</span></code></pre></div>
<pre class="output"><code>2</code></pre>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="dv">3</span><span class="op">//</span><span class="dv">2</span></code></pre></div>
<pre class="output"><code>1</code></pre>
</div>
</aside>
<h2 id="composing-functions">Composing Functions</h2>
<p>Now that we’ve seen how to turn Fahrenheit into Kelvin, it’s easy to turn Kelvin into Celsius:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> kelvin_to_celsius(temp_k):
<span class="cf">return</span> temp_k <span class="op">-</span> <span class="fl">273.15</span>
<span class="bu">print</span>(<span class="st">'absolute zero in Celsius:'</span>, kelvin_to_celsius(<span class="fl">0.0</span>))</code></pre></div>
<pre class="output"><code>absolute zero in Celsius: -273.15</code></pre>
<p>What about converting Fahrenheit to Celsius? We could write out the formula, but we don’t need to. Instead, we can <a href="reference.html#compose">compose</a> the two functions we have already created:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> fahr_to_celsius(temp_f):
temp_k <span class="op">=</span> fahr_to_kelvin(temp_f)
result <span class="op">=</span> kelvin_to_celsius(temp_k)
<span class="cf">return</span> result
<span class="bu">print</span>(<span class="st">'freezing point of water in Celsius:'</span>, fahr_to_celsius(<span class="fl">32.0</span>))</code></pre></div>
<pre class="output"><code>freezing point of water in Celsius: 0.0</code></pre>
<p>This is our first taste of how larger programs are built: we define basic operations, then combine them in ever-large chunks to get the effect we want. Real-life functions will usually be larger than the ones shown here — typically half a dozen to a few dozen lines — but they shouldn’t ever be much longer than that, or the next person who reads it won’t be able to understand what’s going on.</p>
<h2 id="tidying-up">Tidying up</h2>
<p>Now that we know how to wrap bits of code up in functions, we can make our inflammation analysis easier to read and easier to reuse. First, let’s make an <code>analyze</code> function that generates our plots:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> analyze(filename):
data <span class="op">=</span> numpy.loadtxt(fname<span class="op">=</span>filename, delimiter<span class="op">=</span><span class="st">','</span>)
fig <span class="op">=</span> matplotlib.pyplot.figure(figsize<span class="op">=</span>(<span class="fl">10.0</span>, <span class="fl">3.0</span>))
axes1 <span class="op">=</span> fig.add_subplot(<span class="dv">1</span>, <span class="dv">3</span>, <span class="dv">1</span>)
axes2 <span class="op">=</span> fig.add_subplot(<span class="dv">1</span>, <span class="dv">3</span>, <span class="dv">2</span>)
axes3 <span class="op">=</span> fig.add_subplot(<span class="dv">1</span>, <span class="dv">3</span>, <span class="dv">3</span>)
axes1.set_ylabel(<span class="st">'average'</span>)
axes1.plot(data.mean(axis<span class="op">=</span><span class="dv">0</span>))
axes2.set_ylabel(<span class="st">'max'</span>)
axes2.plot(data.<span class="bu">max</span>(axis<span class="op">=</span><span class="dv">0</span>))
axes3.set_ylabel(<span class="st">'min'</span>)
axes3.plot(data.<span class="bu">min</span>(axis<span class="op">=</span><span class="dv">0</span>))
fig.tight_layout()
matplotlib.pyplot.show()</code></pre></div>
<p>and another function called <code>detect_problems</code> that checks for those systematics we noticed:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> detect_problems(filename):
data <span class="op">=</span> numpy.loadtxt(fname<span class="op">=</span>filename, delimiter<span class="op">=</span><span class="st">','</span>)
<span class="cf">if</span> data.<span class="bu">max</span>(axis<span class="op">=</span><span class="dv">0</span>)[<span class="dv">0</span>] <span class="op">==</span> <span class="dv">0</span> <span class="op">and</span> data.<span class="bu">max</span>(axis<span class="op">=</span><span class="dv">0</span>)[<span class="dv">20</span>] <span class="op">==</span> <span class="dv">20</span>:
<span class="bu">print</span>(<span class="st">'Suspicious looking maxima!'</span>)
<span class="cf">elif</span> data.<span class="bu">min</span>(axis<span class="op">=</span><span class="dv">0</span>).<span class="bu">sum</span>() <span class="op">==</span> <span class="dv">0</span>:
<span class="bu">print</span>(<span class="st">'Minima add up to zero!'</span>)
<span class="cf">else</span>:
<span class="bu">print</span>(<span class="st">'Seems OK!'</span>)</code></pre></div>
<p>Notice that rather than jumbling this code together in one giant <code>for</code> loop, we can now read and reuse both ideas separately. We can reproduce the previous analysis with a much simpler <code>for</code> loop:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="cf">for</span> f <span class="op">in</span> filenames[:<span class="dv">3</span>]:
<span class="bu">print</span>(f)
analyze(f)
detect_problems(f)</code></pre></div>
<p>By giving our functions human-readable names, we can more easily read and understand what is happening in the <code>for</code> loop. Even better, if at some later date we want to use either of those pieces of code again, we can do so in a single line.</p>
<h2 id="testing-and-documenting">Testing and Documenting</h2>
<p>Once we start putting things in functions so that we can re-use them, we need to start testing that those functions are working correctly. To see how to do this, let’s write a function to center a dataset around a particular value:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> center(data, desired):
<span class="cf">return</span> (data <span class="op">-</span> data.mean()) <span class="op">+</span> desired</code></pre></div>
<p>We could test this on our actual data, but since we don’t know what the values ought to be, it will be hard to tell if the result was correct. Instead, let’s use NumPy to create a matrix of 0’s and then center that around 3:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">z <span class="op">=</span> numpy.zeros((<span class="dv">2</span>,<span class="dv">2</span>))
<span class="bu">print</span>(center(z, <span class="dv">3</span>))</code></pre></div>
<pre class="output"><code>[[ 3. 3.]
[ 3. 3.]]</code></pre>
<p>That looks right, so let’s try <code>center</code> on our real data:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">data <span class="op">=</span> numpy.loadtxt(fname<span class="op">=</span><span class="st">'inflammation-01.csv'</span>, delimiter<span class="op">=</span><span class="st">','</span>)
<span class="bu">print</span>(center(data, <span class="dv">0</span>))</code></pre></div>
<pre class="output"><code>[[-6.14875 -6.14875 -5.14875 ..., -3.14875 -6.14875 -6.14875]
[-6.14875 -5.14875 -4.14875 ..., -5.14875 -6.14875 -5.14875]
[-6.14875 -5.14875 -5.14875 ..., -4.14875 -5.14875 -5.14875]
...,
[-6.14875 -5.14875 -5.14875 ..., -5.14875 -5.14875 -5.14875]
[-6.14875 -6.14875 -6.14875 ..., -6.14875 -4.14875 -6.14875]
[-6.14875 -6.14875 -5.14875 ..., -5.14875 -5.14875 -6.14875]]</code></pre>
<p>It’s hard to tell from the default output whether the result is correct, but there are a few simple tests that will reassure us:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">'original min, mean, and max are:'</span>, data.<span class="bu">min</span>(), data.mean(), data.<span class="bu">max</span>())
centered <span class="op">=</span> center(data, <span class="dv">0</span>)
<span class="bu">print</span>(<span class="st">'min, mean, and and max of centered data are:'</span>, centered.<span class="bu">min</span>(), centered.mean(), centered.<span class="bu">max</span>())</code></pre></div>
<pre class="output"><code>original min, mean, and max are: 0.0 6.14875 20.0
min, mean, and and max of centered data are: -6.14875 2.84217094304e-16 13.85125</code></pre>
<p>That seems almost right: the original mean was about 6.1, so the lower bound from zero is now about -6.1. The mean of the centered data isn’t quite zero — we’ll explore why not in the challenges — but it’s pretty close. We can even go further and check that the standard deviation hasn’t changed:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">'std dev before and after:'</span>, data.std(), centered.std())</code></pre></div>
<pre class="output"><code>std dev before and after: 4.61383319712 4.61383319712</code></pre>
<p>Those values look the same, but we probably wouldn’t notice if they were different in the sixth decimal place. Let’s do this instead:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">'difference in standard deviations before and after:'</span>, data.std() <span class="op">-</span> centered.std())</code></pre></div>
<pre class="output"><code>difference in standard deviations before and after: -3.5527136788e-15</code></pre>
<p>Again, the difference is very small. It’s still possible that our function is wrong, but it seems unlikely enough that we should probably get back to doing our analysis. We have one more task first, though: we should write some <a href="reference.html#documentation">documentation</a> for our function to remind ourselves later what it’s for and how to use it.</p>
<p>The usual way to put documentation in software is to add <a href="reference.html#comment">comments</a> like this:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="co"># center(data, desired): return a new array containing the original data centered around the desired value.</span>
<span class="kw">def</span> center(data, desired):
<span class="cf">return</span> (data <span class="op">-</span> data.mean()) <span class="op">+</span> desired</code></pre></div>
<p>There’s a better way, though. If the first thing in a function is a string that isn’t assigned to a variable, that string is attached to the function as its documentation:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> center(data, desired):
<span class="co">'''Return a new array containing the original data centered around the desired value.'''</span>
<span class="cf">return</span> (data <span class="op">-</span> data.mean()) <span class="op">+</span> desired</code></pre></div>
<p>This is better because we can now ask Python’s built-in help system to show us the documentation for the function:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">help</span>(center)</code></pre></div>
<pre class="output"><code>Help on function center in module __main__:
center(data, desired)
Return a new array containing the original data centered around the desired value.</code></pre>
<p>A string like this is called a <a href="reference.html#docstring">docstring</a>. We don’t need to use triple quotes when we write one, but if we do, we can break the string across multiple lines:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> center(data, desired):
<span class="co">'''Return a new array containing the original data centered around the desired value.</span>
<span class="co"> Example: center([1, 2, 3], 0) => [-1, 0, 1]'''</span>
<span class="cf">return</span> (data <span class="op">-</span> data.mean()) <span class="op">+</span> desired
<span class="bu">help</span>(center)</code></pre></div>
<pre class="output"><code>Help on function center in module __main__:
center(data, desired)
Return a new array containing the original data centered around the desired value.
Example: center([1, 2, 3], 0) => [-1, 0, 1]</code></pre>
<h2 id="defining-defaults">Defining Defaults</h2>
<p>We have passed parameters to functions in two ways: directly, as in <code>type(data)</code>, and by name, as in <code>numpy.loadtxt(fname='something.csv', delimiter=',')</code>. In fact, we can pass the filename to <code>loadtxt</code> without the <code>fname=</code>:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">numpy.loadtxt(<span class="st">'inflammation-01.csv'</span>, delimiter<span class="op">=</span><span class="st">','</span>)</code></pre></div>
<pre class="output"><code>array([[ 0., 0., 1., ..., 3., 0., 0.],
[ 0., 1., 2., ..., 1., 0., 1.],
[ 0., 1., 1., ..., 2., 1., 1.],
...,
[ 0., 1., 1., ..., 1., 1., 1.],
[ 0., 0., 0., ..., 0., 2., 0.],
[ 0., 0., 1., ..., 1., 1., 0.]])</code></pre>
<p>but we still need to say <code>delimiter=</code>:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">numpy.loadtxt(<span class="st">'inflammation-01.csv'</span>, <span class="st">','</span>)</code></pre></div>
<pre class="error"><code>---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-e3bc6cf4fd6a> in <module>()
----> 1 numpy.loadtxt('inflammation-01.csv', ',')
/Users/gwilson/anaconda/lib/python2.7/site-packages/numpy/lib/npyio.pyc in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin)
775 try:
776 # Make sure we're dealing with a proper dtype
--> 777 dtype = np.dtype(dtype)
778 defconv = _getconv(dtype)
779
TypeError: data type "," not understood</code></pre>
<p>To understand what’s going on, and make our own functions easier to use, let’s re-define our <code>center</code> function like this:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> center(data, desired<span class="op">=</span><span class="fl">0.0</span>):
<span class="co">'''Return a new array containing the original data centered around the desired value (0 by default).</span>
<span class="co"> Example: center([1, 2, 3], 0) => [-1, 0, 1]'''</span>
<span class="cf">return</span> (data <span class="op">-</span> data.mean()) <span class="op">+</span> desired</code></pre></div>
<p>The key change is that the second parameter is now written <code>desired=0.0</code> instead of just <code>desired</code>. If we call the function with two arguments, it works as it did before:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">test_data <span class="op">=</span> numpy.zeros((<span class="dv">2</span>, <span class="dv">2</span>))
<span class="bu">print</span>(center(test_data, <span class="dv">3</span>))</code></pre></div>
<pre class="output"><code>[[ 3. 3.]
[ 3. 3.]]</code></pre>
<p>But we can also now call it with just one parameter, in which case <code>desired</code> is automatically assigned the <a href="reference.html#default-value">default value</a> of 0.0:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">more_data <span class="op">=</span> <span class="dv">5</span> <span class="op">+</span> numpy.zeros((<span class="dv">2</span>, <span class="dv">2</span>))
<span class="bu">print</span>(<span class="st">'data before centering:'</span>)
<span class="bu">print</span>(more_data)
<span class="bu">print</span>(<span class="st">'centered data:'</span>)
<span class="bu">print</span>(center(more_data))</code></pre></div>
<pre class="output"><code>data before centering:
[[ 5. 5.]
[ 5. 5.]]
centered data:
[[ 0. 0.]
[ 0. 0.]]</code></pre>
<p>This is handy: if we usually want a function to work one way, but occasionally need it to do something else, we can allow people to pass a parameter when they need to but provide a default to make the normal case easier. The example below shows how Python matches values to parameters:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> display(a<span class="op">=</span><span class="dv">1</span>, b<span class="op">=</span><span class="dv">2</span>, c<span class="op">=</span><span class="dv">3</span>):
<span class="bu">print</span>(<span class="st">'a:'</span>, a, <span class="st">'b:'</span>, b, <span class="st">'c:'</span>, c)
<span class="bu">print</span>(<span class="st">'no parameters:'</span>)
display()
<span class="bu">print</span>(<span class="st">'one parameter:'</span>)
display(<span class="dv">55</span>)
<span class="bu">print</span>(<span class="st">'two parameters:'</span>)
display(<span class="dv">55</span>, <span class="dv">66</span>)</code></pre></div>
<pre class="output"><code>no parameters:
a: 1 b: 2 c: 3
one parameter:
a: 55 b: 2 c: 3
two parameters:
a: 55 b: 66 c: 3</code></pre>
<p>As this example shows, parameters are matched up from left to right, and any that haven’t been given a value explicitly get their default value. We can override this behavior by naming the value as we pass it in:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(<span class="st">'only setting the value of c'</span>)
display(c<span class="op">=</span><span class="dv">77</span>)</code></pre></div>
<pre class="output"><code>only setting the value of c
a: 1 b: 2 c: 77</code></pre>
<p>With that in hand, let’s look at the help for <code>numpy.loadtxt</code>:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">help</span>(numpy.loadtxt)</code></pre></div>
<pre class="output"><code>Help on function loadtxt in module numpy.lib.npyio:
loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
Load data from a text file.
Each row in the text file must have the same number of values.
Parameters
----------
fname : file or str
File, filename, or generator to read. If the filename extension is
``.gz`` or ``.bz2``, the file is first decompressed. Note that
generators should return byte strings for Python 3k.
dtype : data-type, optional
Data-type of the resulting array; default: float. If this is a
record data-type, the resulting array will be 1-dimensional, and
each row will be interpreted as an element of the array. In this
case, the number of columns used must match the number of fields in
the data-type.
comments : str, optional
The character used to indicate the start of a comment;
default: '#'.
delimiter : str, optional
The string used to separate values. By default, this is any
whitespace.
converters : dict, optional
A dictionary mapping column number to a function that will convert
that column to a float. E.g., if column 0 is a date string:
``converters = {0: datestr2num}``. Converters can also be used to
provide a default value for missing data (but see also `genfromtxt`):
``converters = {3: lambda s: float(s.strip() or 0)}``. Default: None.
skiprows : int, optional
Skip the first `skiprows` lines; default: 0.
usecols : sequence, optional
Which columns to read, with 0 being the first. For example,
``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
The default, None, results in all columns being read.
unpack : bool, optional
If True, the returned array is transposed, so that arguments may be
unpacked using ``x, y, z = loadtxt(...)``. When used with a record
data-type, arrays are returned for each field. Default is False.
ndmin : int, optional
The returned array will have at least `ndmin` dimensions.
Otherwise mono-dimensional axes will be squeezed.
Legal values: 0 (default), 1 or 2.
.. versionadded:: 1.6.0
Returns
-------
out : ndarray
Data read from the text file.
See Also
--------
load, fromstring, fromregex
genfromtxt : Load data with missing values handled as specified.
scipy.io.loadmat : reads MATLAB data files
Notes
-----
This function aims to be a fast reader for simply formatted files. The
`genfromtxt` function provides more sophisticated handling of, e.g.,
lines with missing values.
Examples
--------
>>> from StringIO import StringIO # StringIO behaves like a file object
>>> c = StringIO("0 1\n2 3")
>>> np.loadtxt(c)
array([[ 0., 1.],
[ 2., 3.]])
>>> d = StringIO("M 21 72\nF 35 58")
>>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
... 'formats': ('S1', 'i4', 'f4')})
array([('M', 21, 72.0), ('F', 35, 58.0)],
dtype=[('gender', '|S1'), ('age', '<i4'), ('weight', '<f4')])
>>> c = StringIO("1,0,2\n3,0,4")
>>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
>>> x
array([ 1., 3.])
>>> y
array([ 2., 4.])</code></pre>
<p>There’s a lot of information here, but the most important part is the first couple of lines:</p>
<pre class="output"><code>loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None,
unpack=False, ndmin=0)</code></pre>
<p>This tells us that <code>loadtxt</code> has one parameter called <code>fname</code> that doesn’t have a default value, and eight others that do. If we call the function like this:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">numpy.loadtxt(<span class="st">'inflammation-01.csv'</span>, <span class="st">','</span>)</code></pre></div>
<p>then the filename is assigned to <code>fname</code> (which is what we want), but the delimiter string <code>','</code> is assigned to <code>dtype</code> rather than <code>delimiter</code>, because <code>dtype</code> is the second parameter in the list. However ‘,’ isn’t a known <code>dtype</code> so our code produced an error message when we tried to run it. When we call <code>loadtxt</code> we don’t have to provide <code>fname=</code> for the filename because it’s the first item in the list, but if we want the ‘,’ to be assigned to the variable <code>delimiter</code>, we <em>do</em> have to provide <code>delimiter=</code> for the second parameter since <code>delimiter</code> is not the second parameter in the list.</p>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="combining-strings"><span class="glyphicon glyphicon-pencil"></span>Combining strings</h2>
</div>
<div class="panel-body">
<p>“Adding” two strings produces their concatenation: <code>'a' + 'b'</code> is <code>'ab'</code>. Write a function called <code>fence</code> that takes two parameters called <code>original</code> and <code>wrapper</code> and returns a new string that has the wrapper character at the beginning and end of the original. A call to your function should look like this:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(fence(<span class="st">'name'</span>, <span class="st">'*'</span>))</code></pre></div>
<pre class="output"><code>*name*</code></pre>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="selecting-characters-from-strings"><span class="glyphicon glyphicon-pencil"></span>Selecting characters from strings</h2>
</div>
<div class="panel-body">
<p>If the variable <code>s</code> refers to a string, then <code>s[0]</code> is the string’s first character and <code>s[-1]</code> is its last. Write a function called <code>outer</code> that returns a string made up of just the first and last characters of its input. A call to your function should look like this:</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python"><span class="bu">print</span>(outer(<span class="st">'helium'</span>))</code></pre></div>
<pre class="output"><code>hm</code></pre>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="rescaling-an-array"><span class="glyphicon glyphicon-pencil"></span>Rescaling an array</h2>
</div>
<div class="panel-body">
<p>Write a function <code>rescale</code> that takes an array as input and returns a corresponding array of values scaled to lie in the range 0.0 to 1.0. (Hint: If <span class="math inline"><em>L</em></span> and <span class="math inline"><em>H</em></span> are the lowest and highest values in the original array, then the replacement for a value <span class="math inline"><em>v</em></span> should be <span class="math inline">(<em>v</em> − <em>L</em>)/(<em>H</em> − <em>L</em>)</span>.)</p>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="testing-and-documenting-your-function"><span class="glyphicon glyphicon-pencil"></span>Testing and documenting your function</h2>
</div>
<div class="panel-body">
<p>Run the commands <code>help(numpy.arange)</code> and <code>help(numpy.linspace)</code> to see how to use these functions to generate regularly-spaced values, then use those values to test your <code>rescale</code> function. Once you’ve successfully tested your function, add a docstring that explains what it does.</p>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="defining-defaults-1"><span class="glyphicon glyphicon-pencil"></span>Defining defaults</h2>
</div>
<div class="panel-body">
<p>Rewrite the <code>rescale</code> function so that it scales data to lie between 0.0 and 1.0 by default, but will allow the caller to specify lower and upper bounds if they want. Compare your implementation to your neighbor’s: do the two functions always behave the same way?</p>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="variables-inside-and-outside-functions"><span class="glyphicon glyphicon-pencil"></span>Variables inside and outside functions</h2>
</div>
<div class="panel-body">
<p>What does the following piece of code display when run - and why?</p>
<div class="sourceCode"><pre class="sourceCode python"><code class="sourceCode python">f <span class="op">=</span> <span class="dv">0</span>
k <span class="op">=</span> <span class="dv">0</span>
<span class="kw">def</span> f2k(f):
k <span class="op">=</span> ((f<span class="dv">-32</span>)<span class="op">*</span>(<span class="fl">5.0</span><span class="op">/</span><span class="fl">9.0</span>)) <span class="op">+</span> <span class="fl">273.15</span>
<span class="cf">return</span> k
f2k(<span class="dv">8</span>)
f2k(<span class="dv">41</span>)
f2k(<span class="dv">32</span>)
<span class="bu">print</span>(k)</code></pre></div>
</div>
</section>
</div>
</div>
</article>
<div class="footer">
<a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
<a class="label swc-blue-bg" href="https://github.com/swcarpentry/python-novice-inflammation">Source</a>
<a class="label swc-blue-bg" href="mailto:admin@software-carpentry.org">Contact</a>
<a class="label swc-blue-bg" href="LICENSE.html">License</a>
</div>
</div>
<!-- Javascript placed at the end of the document so the pages load faster -->
<script src="http://software-carpentry.org/v5/js/jquery-1.9.1.min.js"></script>
<script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
</body>
</html>