novice: Copy-paste from origin/master
[swc-modular-python.git] / 02-func.ipynb
1 {
2  "metadata": {
3   "name": ""
4  },
5  "nbformat": 3,
6  "nbformat_minor": 0,
7  "worksheets": [
8   {
9    "cells": [
10     {
11      "cell_type": "heading",
12      "level": 2,
13      "metadata": {
14       "cell_tags": []
15      },
16      "source": [
17       "Creating Functions"
18      ]
19     },
20     {
21      "cell_type": "markdown",
22      "metadata": {
23       "cell_tags": []
24      },
25      "source": [
26       "If we only had one data set to analyze,\n",
27       "it would probably be faster to load the file into a spreadsheet\n",
28       "and use that to plot some simple statistics.\n",
29       "But we have twelve files to check,\n",
30       "and may have more in future.\n",
31       "In this lesson,\n",
32       "we'll learn how to write a function\n",
33       "so that we can repeat several operations with a single command."
34      ]
35     },
36     {
37      "cell_type": "markdown",
38      "metadata": {
39       "cell_tags": [
40        "objectives"
41       ]
42      },
43      "source": [
44       "#### Objectives\n",
45       "\n",
46       "*   Define a function that takes parameters.\n",
47       "*   Return a value from a function.\n",
48       "*   Test and debug a function.\n",
49       "*   Explain what a call stack is, and trace changes to the call stack as functions are called.\n",
50       "*   Set default values for function parameters.\n",
51       "*   Explain why we should divide programs into small, single-purpose functions."
52      ]
53     },
54     {
55      "cell_type": "heading",
56      "level": 3,
57      "metadata": {
58       "cell_tags": []
59      },
60      "source": [
61       "Defining a Function"
62      ]
63     },
64     {
65      "cell_type": "markdown",
66      "metadata": {
67       "cell_tags": []
68      },
69      "source": [
70       "Let's start by defining a function `fahr_to_kelvin` that converts temperatures from Fahrenheit to Kelvin:"
71      ]
72     },
73     {
74      "cell_type": "code",
75      "collapsed": false,
76      "input": [
77       "def fahr_to_kelvin(temp):\n",
78       "    return ((temp - 32) * (5/9)) + 273.15"
79      ],
80      "language": "python",
81      "metadata": {
82       "cell_tags": []
83      },
84      "outputs": [],
85      "prompt_number": 1
86     },
87     {
88      "cell_type": "markdown",
89      "metadata": {
90       "cell_tags": []
91      },
92      "source": [
93       "The definition opens with the word `def`,\n",
94       "which is followed by the name of the function\n",
95       "and a parenthesized list of parameter names.\n",
96       "The [body](../../gloss.html#function-body) of the function—the\n",
97       "statements that are executed when it runs—is indented below the definition line,\n",
98       "typically by four spaces.\n",
99       "\n",
100       "When we call the function,\n",
101       "the values we pass to it are assigned to those variables\n",
102       "so that we can use them inside the function.\n",
103       "Inside the function,\n",
104       "we use a [return statement](../../gloss.html#return-statement) to send a result back to whoever asked for it.\n",
105       "\n",
106       "Let's try running our function.\n",
107       "Calling our own function is no different from calling any other function:"
108      ]
109     },
110     {
111      "cell_type": "code",
112      "collapsed": false,
113      "input": [
114       "print 'freezing point of water:', fahr_to_kelvin(32)\n",
115       "print 'boiling point of water:', fahr_to_kelvin(212)"
116      ],
117      "language": "python",
118      "metadata": {
119       "cell_tags": []
120      },
121      "outputs": [
122       {
123        "output_type": "stream",
124        "stream": "stdout",
125        "text": [
126         "freezing point of water: 273.15\n",
127         "boiling point of water: 273.15\n"
128        ]
129       }
130      ],
131      "prompt_number": 2
132     },
133     {
134      "cell_type": "markdown",
135      "metadata": {},
136      "source": [
137       "We've successfully called the function that we defined,\n",
138       "and we have access to the value that we returned.\n",
139       "Unfortunately, the value returned doesn't look right.\n",
140       "What went wrong?"
141      ]
142     },
143     {
144      "cell_type": "heading",
145      "level": 3,
146      "metadata": {},
147      "source": [
148       "Debugging a Function"
149      ]
150     },
151     {
152      "cell_type": "markdown",
153      "metadata": {},
154      "source": [
155       "*Debugging* is when we fix a piece of code\n",
156       "that we know is working incorrectly.\n",
157       "In this case, we know that `fahr_to_kelvin`\n",
158       "is giving us the wrong answer,\n",
159       "so let's find out why.\n",
160       "\n",
161       "For big pieces of code,\n",
162       "there are tools called *debuggers* that aid in this process.\n",
163       "\n",
164       "We just have a short function,\n",
165       "so we'll debug by choosing some parameter value,\n",
166       "breaking our function into small parts,\n",
167       "and printing out the value of each part."
168      ]
169     },
170     {
171      "cell_type": "code",
172      "collapsed": false,
173      "input": [
174       "# We'll use temp = 212, the boiling point of water, which was incorrect\n",
175       "print \"212 - 32:\", 212 - 32"
176      ],
177      "language": "python",
178      "metadata": {},
179      "outputs": [
180       {
181        "output_type": "stream",
182        "stream": "stdout",
183        "text": [
184         "212 - 32: 180\n"
185        ]
186       }
187      ],
188      "prompt_number": 3
189     },
190     {
191      "cell_type": "code",
192      "collapsed": false,
193      "input": [
194       "print \"(212 - 32) * (5/9):\", (212 - 32) * (5/9)"
195      ],
196      "language": "python",
197      "metadata": {},
198      "outputs": [
199       {
200        "output_type": "stream",
201        "stream": "stdout",
202        "text": [
203         "(212 - 32) * (5/9): 0\n"
204        ]
205       }
206      ],
207      "prompt_number": 4
208     },
209     {
210      "cell_type": "markdown",
211      "metadata": {},
212      "source": [
213       "Aha! The problem comes when we multiply by `5/9`.\n",
214       "This is because `5/9` is actually 0."
215      ]
216     },
217     {
218      "cell_type": "code",
219      "collapsed": false,
220      "input": [
221       "5/9"
222      ],
223      "language": "python",
224      "metadata": {},
225      "outputs": [
226       {
227        "metadata": {},
228        "output_type": "pyout",
229        "prompt_number": 5,
230        "text": [
231         "0"
232        ]
233       }
234      ],
235      "prompt_number": 5
236     },
237     {
238      "cell_type": "markdown",
239      "metadata": {
240       "cell_tags": []
241      },
242      "source": [
243       "Computers store numbers in one of two ways:\n",
244       "as [integers](../../gloss.html#integer)\n",
245       "or as [floating-point numbers](../../gloss.html#float) (or floats).\n",
246       "The first are the numbers we usually count with;\n",
247       "the second have fractional parts.\n",
248       "Addition, subtraction and multiplication work on both as we'd expect,\n",
249       "but division works differently.\n",
250       "If we divide one integer by another,\n",
251       "we get the quotient without the remainder:"
252      ]
253     },
254     {
255      "cell_type": "code",
256      "collapsed": false,
257      "input": [
258       "print '10/3 is:', 10/3"
259      ],
260      "language": "python",
261      "metadata": {
262       "cell_tags": []
263      },
264      "outputs": [
265       {
266        "output_type": "stream",
267        "stream": "stdout",
268        "text": [
269         "10/3 is: 3\n"
270        ]
271       }
272      ],
273      "prompt_number": 6
274     },
275     {
276      "cell_type": "markdown",
277      "metadata": {
278       "cell_tags": []
279      },
280      "source": [
281       "If either part of the division is a float,\n",
282       "on the other hand,\n",
283       "the computer creates a floating-point answer:"
284      ]
285     },
286     {
287      "cell_type": "code",
288      "collapsed": false,
289      "input": [
290       "print '10.0/3 is:', 10.0/3"
291      ],
292      "language": "python",
293      "metadata": {
294       "cell_tags": []
295      },
296      "outputs": [
297       {
298        "output_type": "stream",
299        "stream": "stdout",
300        "text": [
301         "10.0/3 is: 3.33333333333\n"
302        ]
303       }
304      ],
305      "prompt_number": 7
306     },
307     {
308      "cell_type": "markdown",
309      "metadata": {
310       "cell_tags": []
311      },
312      "source": [
313       "The computer does this for historical reasons:\n",
314       "integer operations were much faster on early machines,\n",
315       "and this behavior is actually useful in a lot of situations.\n",
316       "It's still confusing,\n",
317       "though,\n",
318       "so Python 3 produces a floating-point answer when dividing integers if it needs to.\n",
319       "We're still using Python 2.7 in this class,\n",
320       "though,\n",
321       "so if we want `5/9` to give us the right answer,\n",
322       "we have to write it as `5.0/9`, `5/9.0`, or some other variation."
323      ]
324     },
325     {
326      "cell_type": "markdown",
327      "metadata": {},
328      "source": [
329       "Let's fix our `fahr_to_kelvin` function with this new knowledge."
330      ]
331     },
332     {
333      "cell_type": "code",
334      "collapsed": false,
335      "input": [
336       "def fahr_to_kelvin(temp):\n",
337       "    return ((temp - 32) * (5.0/9.0)) + 273.15\n",
338       "\n",
339       "print 'freezing point of water:', fahr_to_kelvin(32)\n",
340       "print 'boiling point of water:', fahr_to_kelvin(212)"
341      ],
342      "language": "python",
343      "metadata": {},
344      "outputs": [
345       {
346        "output_type": "stream",
347        "stream": "stdout",
348        "text": [
349         "freezing point of water: 273.15\n",
350         "boiling point of water: 373.15\n"
351        ]
352       }
353      ],
354      "prompt_number": 8
355     },
356     {
357      "cell_type": "markdown",
358      "metadata": {
359       "cell_tags": []
360      },
361      "source": [
362       "It works!"
363      ]
364     },
365     {
366      "cell_type": "heading",
367      "level": 3,
368      "metadata": {},
369      "source": [
370       "Composing Functions"
371      ]
372     },
373     {
374      "cell_type": "markdown",
375      "metadata": {},
376      "source": [
377       "Now that we've seen how to turn Fahrenheit into Kelvin,\n",
378       "it's easy to turn Kelvin into Celsius:"
379      ]
380     },
381     {
382      "cell_type": "code",
383      "collapsed": false,
384      "input": [
385       "def kelvin_to_celsius(temp):\n",
386       "    return temp - 273.15\n",
387       "\n",
388       "print 'absolute zero in Celsius:', kelvin_to_celsius(0.0)"
389      ],
390      "language": "python",
391      "metadata": {
392       "cell_tags": []
393      },
394      "outputs": [
395       {
396        "output_type": "stream",
397        "stream": "stdout",
398        "text": [
399         "absolute zero in Celsius: -273.15\n"
400        ]
401       }
402      ],
403      "prompt_number": 9
404     },
405     {
406      "cell_type": "markdown",
407      "metadata": {
408       "cell_tags": []
409      },
410      "source": [
411       "What about converting Fahrenheit to Celsius?\n",
412       "We could write out the formula,\n",
413       "but we don't need to.\n",
414       "Instead,\n",
415       "we can [compose](../../gloss.html#function-composition) the two functions we have already created:"
416      ]
417     },
418     {
419      "cell_type": "code",
420      "collapsed": false,
421      "input": [
422       "def fahr_to_celsius(temp):\n",
423       "    temp_k = fahr_to_kelvin(temp)\n",
424       "    result = kelvin_to_celsius(temp_k)\n",
425       "    return result\n",
426       "\n",
427       "print 'freezing point of water in Celsius:', fahr_to_celsius(32.0)"
428      ],
429      "language": "python",
430      "metadata": {
431       "cell_tags": []
432      },
433      "outputs": [
434       {
435        "output_type": "stream",
436        "stream": "stdout",
437        "text": [
438         "freezing point of water in Celsius: 0.0\n"
439        ]
440       }
441      ],
442      "prompt_number": 10
443     },
444     {
445      "cell_type": "markdown",
446      "metadata": {
447       "cell_tags": []
448      },
449      "source": [
450       "This is our first taste of how larger programs are built:\n",
451       "we define basic operations,\n",
452       "then combine them in ever-large chunks to get the effect we want.\n",
453       "Real-life functions will usually be larger than the ones shown here—typically half a dozen to a few dozen lines—but\n",
454       "they shouldn't ever be much longer than that,\n",
455       "or the next person who reads it won't be able to understand what's going on."
456      ]
457     },
458     {
459      "cell_type": "markdown",
460      "metadata": {
461       "cell_tags": [
462        "challenges"
463       ]
464      },
465      "source": [
466       "#### Challenges\n",
467       "\n",
468       "1.  \"Adding\" two strings produces their concatention:\n",
469       "    `'a' + 'b'` is `'ab'`.\n",
470       "    Write a function called `fence` that takes two parameters called `original` and `wrapper`\n",
471       "    and returns a new string that has the wrapper character at the beginning and end of the original:\n",
472       "\n",
473       "    ~~~python\n",
474       "    print fence('name', '*')\n",
475       "    *name*\n",
476       "    ~~~\n",
477       "\n",
478       "1.  If the variable `s` refers to a string,\n",
479       "    then `s[0]` is the string's first character\n",
480       "    and `s[-1]` is its last.\n",
481       "    Write a function called `outer`\n",
482       "    that returns a string made up of just the first and last characters of its input:\n",
483       "\n",
484       "    ~~~python\n",
485       "    print outer('helium')\n",
486       "    hm\n",
487       "    ~~~"
488      ]
489     },
490     {
491      "cell_type": "heading",
492      "level": 3,
493      "metadata": {
494       "cell_tags": []
495      },
496      "source": [
497       "The Call Stack"
498      ]
499     },
500     {
501      "cell_type": "markdown",
502      "metadata": {
503       "cell_tags": []
504      },
505      "source": [
506       "Let's take a closer look at what happens when we call `fahr_to_celsius(32.0)`.\n",
507       "To make things clearer,\n",
508       "we'll start by putting the initial value 32.0 in a variable\n",
509       "and store the final result in one as well:"
510      ]
511     },
512     {
513      "cell_type": "code",
514      "collapsed": false,
515      "input": [
516       "original = 32.0\n",
517       "final = fahr_to_celsius(original)"
518      ],
519      "language": "python",
520      "metadata": {
521       "cell_tags": []
522      },
523      "outputs": [],
524      "prompt_number": 11
525     },
526     {
527      "cell_type": "markdown",
528      "metadata": {
529       "cell_tags": []
530      },
531      "source": [
532       "The diagram below shows what memory looks like after the first line has been executed:"
533      ]
534     },
535     {
536      "cell_type": "markdown",
537      "metadata": {
538       "cell_tags": []
539      },
540      "source": [
541       "<img src=\"files/img/python-call-stack-01.svg\" alt=\"Call Stack (Initial State)\" />"
542      ]
543     },
544     {
545      "cell_type": "markdown",
546      "metadata": {
547       "cell_tags": []
548      },
549      "source": [
550       "When we call `fahr_to_celsius`,\n",
551       "Python *doesn't* create the variable `temp` right away.\n",
552       "Instead,\n",
553       "it creates something called a [stack frame](../../gloss.html#stack-frame)\n",
554       "to keep track of the variables defined by `fahr_to_kelvin`.\n",
555       "Initially,\n",
556       "this stack frame only holds the value of `temp`:"
557      ]
558     },
559     {
560      "cell_type": "markdown",
561      "metadata": {
562       "cell_tags": []
563      },
564      "source": [
565       "<img src=\"files/img/python-call-stack-02.svg\" alt=\"Call Stack Immediately After First Function Call\" />"
566      ]
567     },
568     {
569      "cell_type": "markdown",
570      "metadata": {
571       "cell_tags": []
572      },
573      "source": [
574       "When we call `fahr_to_kelvin` inside `fahr_to_celsius`,\n",
575       "Python creates another stack frame to hold `fahr_to_kelvin`'s variables:"
576      ]
577     },
578     {
579      "cell_type": "markdown",
580      "metadata": {
581       "cell_tags": []
582      },
583      "source": [
584       "<img src=\"files/img/python-call-stack-03.svg\" alt=\"Call Stack During First Nested Function Call\" />"
585      ]
586     },
587     {
588      "cell_type": "markdown",
589      "metadata": {
590       "cell_tags": []
591      },
592      "source": [
593       "It does this because there are now two variables in play called `temp`:\n",
594       "the parameter to `fahr_to_celsius`,\n",
595       "and the parameter to `fahr_to_kelvin`.\n",
596       "Having two variables with the same name in the same part of the program would be ambiguous,\n",
597       "so Python (and every other modern programming language) creates a new stack frame for each function call\n",
598       "to keep that function's variables separate from those defined by other functions.\n",
599       "\n",
600       "When the call to `fahr_to_kelvin` returns a value,\n",
601       "Python throws away `fahr_to_kelvin`'s stack frame\n",
602       "and creates a new variable in the stack frame for `fahr_to_celsius` to hold the temperature in Kelvin:"
603      ]
604     },
605     {
606      "cell_type": "markdown",
607      "metadata": {
608       "cell_tags": []
609      },
610      "source": [
611       "<img src=\"files/img/python-call-stack-04.svg\" alt=\"Call Stack After Return From First Nested Function Call\" />"
612      ]
613     },
614     {
615      "cell_type": "markdown",
616      "metadata": {
617       "cell_tags": []
618      },
619      "source": [
620       "It then calls `kelvin_to_celsius`,\n",
621       "which means it creates a stack frame to hold that function's variables:"
622      ]
623     },
624     {
625      "cell_type": "markdown",
626      "metadata": {
627       "cell_tags": []
628      },
629      "source": [
630       "<img src=\"files/img/python-call-stack-05.svg\" alt=\"Call Stack During Call to Second Nested Function\" />"
631      ]
632     },
633     {
634      "cell_type": "markdown",
635      "metadata": {
636       "cell_tags": []
637      },
638      "source": [
639       "Once again,\n",
640       "Python throws away that stack frame when `kelvin_to_celsius` is done\n",
641       "and creates the variable `result` in the stack frame for `fahr_to_celsius`:"
642      ]
643     },
644     {
645      "cell_type": "markdown",
646      "metadata": {
647       "cell_tags": []
648      },
649      "source": [
650       "<img src=\"files/img/python-call-stack-06.svg\" alt=\"Call Stack After Second Nested Function Returns\" />"
651      ]
652     },
653     {
654      "cell_type": "markdown",
655      "metadata": {
656       "cell_tags": []
657      },
658      "source": [
659       "Finally,\n",
660       "when `fahr_to_celsius` is done,\n",
661       "Python throws away *its* stack frame\n",
662       "and puts its result in a new variable called `final`\n",
663       "that lives in the stack frame we started with:"
664      ]
665     },
666     {
667      "cell_type": "markdown",
668      "metadata": {
669       "cell_tags": []
670      },
671      "source": [
672       "<img src=\"files/img/python-call-stack-07.svg\" alt=\"Call Stack After All Functions Have Finished\" />"
673      ]
674     },
675     {
676      "cell_type": "markdown",
677      "metadata": {
678       "cell_tags": []
679      },
680      "source": [
681       "This final stack frame is always there;\n",
682       "it holds the variables we defined outside the functions in our code.\n",
683       "What it *doesn't* hold is the variables that were in the various stack frames.\n",
684       "If we try to get the value of `temp` after our functions have finished running,\n",
685       "Python tells us that there's no such thing:"
686      ]
687     },
688     {
689      "cell_type": "code",
690      "collapsed": false,
691      "input": [
692       "print 'final value of temp after all function calls:', temp"
693      ],
694      "language": "python",
695      "metadata": {
696       "cell_tags": []
697      },
698      "outputs": [
699       {
700        "ename": "NameError",
701        "evalue": "name 'temp' is not defined",
702        "output_type": "pyerr",
703        "traceback": [
704         "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
705         "\u001b[0;32m<ipython-input-12-ffd9b4dbd5f1>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0;34m'final value of temp after all function calls:'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtemp\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
706         "\u001b[0;31mNameError\u001b[0m: name 'temp' is not defined"
707        ]
708       },
709       {
710        "output_type": "stream",
711        "stream": "stdout",
712        "text": [
713         "final value of temp after all function calls:"
714        ]
715       }
716      ],
717      "prompt_number": 12
718     },
719     {
720      "cell_type": "markdown",
721      "metadata": {
722       "cell_tags": []
723      },
724      "source": [
725       "Why go to all this trouble?\n",
726       "Well,\n",
727       "here's a function called `span` that calculates the difference between\n",
728       "the mininum and maximum values in an array:"
729      ]
730     },
731     {
732      "cell_type": "code",
733      "collapsed": false,
734      "input": [
735       "import numpy\n",
736       "\n",
737       "def span(a):\n",
738       "    diff = a.max() - a.min()\n",
739       "    return diff\n",
740       "\n",
741       "data = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')\n",
742       "print 'span of data', span(data)"
743      ],
744      "language": "python",
745      "metadata": {
746       "cell_tags": []
747      },
748      "outputs": [
749       {
750        "output_type": "stream",
751        "stream": "stdout",
752        "text": [
753         " span of data 20.0\n"
754        ]
755       }
756      ],
757      "prompt_number": 13
758     },
759     {
760      "cell_type": "markdown",
761      "metadata": {
762       "cell_tags": []
763      },
764      "source": [
765       "Notice that `span` assigns a value to a variable called `diff`.\n",
766       "We might very well use a variable with the same name to hold data:"
767      ]
768     },
769     {
770      "cell_type": "code",
771      "collapsed": false,
772      "input": [
773       "diff = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')\n",
774       "print 'span of data:', span(diff)"
775      ],
776      "language": "python",
777      "metadata": {
778       "cell_tags": []
779      },
780      "outputs": [
781       {
782        "output_type": "stream",
783        "stream": "stdout",
784        "text": [
785         "span of data: 20.0\n"
786        ]
787       }
788      ],
789      "prompt_number": 14
790     },
791     {
792      "cell_type": "markdown",
793      "metadata": {
794       "cell_tags": []
795      },
796      "source": [
797       "We don't expect `diff` to have the value 20.0 after this function call,\n",
798       "so the name `diff` cannot refer to the same thing inside `span` as it does in the main body of our program.\n",
799       "And yes,\n",
800       "we could probably choose a different name than `diff` in our main program in this case,\n",
801       "but we don't want to have to read every line of NumPy to see what variable names its functions use\n",
802       "before calling any of those functions,\n",
803       "just in case they change the values of our variables."
804      ]
805     },
806     {
807      "cell_type": "markdown",
808      "metadata": {
809       "cell_tags": []
810      },
811      "source": [
812       "The big idea here is [encapsulation](../../gloss.html#encapsulation),\n",
813       "and it's the key to writing correct, comprehensible programs.\n",
814       "A function's job is to turn several operations into one\n",
815       "so that we can think about a single function call\n",
816       "instead of a dozen or a hundred statements\n",
817       "each time we want to do something.\n",
818       "That only works if functions don't interfere with each other;\n",
819       "if they do,\n",
820       "we have to pay attention to the details once again,\n",
821       "which quickly overloads our short-term memory."
822      ]
823     },
824     {
825      "cell_type": "markdown",
826      "metadata": {
827       "cell_tags": [
828        "challenges"
829       ]
830      },
831      "source": [
832       "#### Challenges\n",
833       "\n",
834       "1.  We previously wrote functions called `fence` and `outer`.\n",
835       "    Draw a diagram showing how the call stack changes when we run the following:\n",
836       "    ~~~python\n",
837       "    print outer(fence('carbon', '+'))\n",
838       "    ~~~"
839      ]
840     },
841     {
842      "cell_type": "heading",
843      "level": 3,
844      "metadata": {
845       "cell_tags": []
846      },
847      "source": [
848       "Testing and Documenting"
849      ]
850     },
851     {
852      "cell_type": "markdown",
853      "metadata": {
854       "cell_tags": []
855      },
856      "source": [
857       "Once we start putting things in functions so that we can re-use them,\n",
858       "we need to start testing that those functions are working correctly.\n",
859       "To see how to do this,\n",
860       "let's write a function to center a dataset around a particular value:"
861      ]
862     },
863     {
864      "cell_type": "code",
865      "collapsed": false,
866      "input": [
867       "def center(data, desired):\n",
868       "    return (data - data.mean()) + desired"
869      ],
870      "language": "python",
871      "metadata": {
872       "cell_tags": []
873      },
874      "outputs": [],
875      "prompt_number": 15
876     },
877     {
878      "cell_type": "markdown",
879      "metadata": {
880       "cell_tags": []
881      },
882      "source": [
883       "We could test this on our actual data,\n",
884       "but since we don't know what the values ought to be,\n",
885       "it will be hard to tell if the result was correct.\n",
886       "Instead,\n",
887       "let's use NumPy to create a matrix of 0's\n",
888       "and then center that around 3:"
889      ]
890     },
891     {
892      "cell_type": "code",
893      "collapsed": false,
894      "input": [
895       "z = numpy.zeros((2,2))\n",
896       "print center(z, 3)"
897      ],
898      "language": "python",
899      "metadata": {
900       "cell_tags": []
901      },
902      "outputs": [
903       {
904        "output_type": "stream",
905        "stream": "stdout",
906        "text": [
907         "[[ 3.  3.]\n",
908         " [ 3.  3.]]\n"
909        ]
910       }
911      ],
912      "prompt_number": 16
913     },
914     {
915      "cell_type": "markdown",
916      "metadata": {
917       "cell_tags": []
918      },
919      "source": [
920       "That looks right,\n",
921       "so let's try `center` on our real data:"
922      ]
923     },
924     {
925      "cell_type": "code",
926      "collapsed": false,
927      "input": [
928       "data = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')\n",
929       "print center(data, 0)"
930      ],
931      "language": "python",
932      "metadata": {
933       "cell_tags": []
934      },
935      "outputs": [
936       {
937        "output_type": "stream",
938        "stream": "stdout",
939        "text": [
940         "[[-6.14875 -6.14875 -5.14875 ..., -3.14875 -6.14875 -6.14875]\n",
941         " [-6.14875 -5.14875 -4.14875 ..., -5.14875 -6.14875 -5.14875]\n",
942         " [-6.14875 -5.14875 -5.14875 ..., -4.14875 -5.14875 -5.14875]\n",
943         " ..., \n",
944         " [-6.14875 -5.14875 -5.14875 ..., -5.14875 -5.14875 -5.14875]\n",
945         " [-6.14875 -6.14875 -6.14875 ..., -6.14875 -4.14875 -6.14875]\n",
946         " [-6.14875 -6.14875 -5.14875 ..., -5.14875 -5.14875 -6.14875]]\n"
947        ]
948       }
949      ],
950      "prompt_number": 17
951     },
952     {
953      "cell_type": "markdown",
954      "metadata": {
955       "cell_tags": []
956      },
957      "source": [
958       "It's hard to tell from the default output whether the result is correct,\n",
959       "but there are a few simple tests that will reassure us:"
960      ]
961     },
962     {
963      "cell_type": "code",
964      "collapsed": false,
965      "input": [
966       "print 'original min, mean, and max are:', data.min(), data.mean(), data.max()\n",
967       "centered = center(data, 0)\n",
968       "print 'min, mean, and and max of centered data are:', centered.min(), centered.mean(), centered.max()"
969      ],
970      "language": "python",
971      "metadata": {
972       "cell_tags": []
973      },
974      "outputs": [
975       {
976        "output_type": "stream",
977        "stream": "stdout",
978        "text": [
979         "original min, mean, and max are: 0.0 6.14875 20.0\n",
980         "min, mean, and and max of centered data are: -6.14875 -3.49054118942e-15 13.85125\n"
981        ]
982       }
983      ],
984      "prompt_number": 18
985     },
986     {
987      "cell_type": "markdown",
988      "metadata": {
989       "cell_tags": []
990      },
991      "source": [
992       "That seems almost right:\n",
993       "the original mean was about 6.1,\n",
994       "so the lower bound from zero is how about -6.1.\n",
995       "The mean of the centered data isn't quite zero&mdash;we'll explore why not in the challenges&mdash;but it's pretty close.\n",
996       "We can even go further and check that the standard deviation hasn't changed:"
997      ]
998     },
999     {
1000      "cell_type": "code",
1001      "collapsed": false,
1002      "input": [
1003       "print 'std dev before and after:', data.std(), centered.std()"
1004      ],
1005      "language": "python",
1006      "metadata": {
1007       "cell_tags": []
1008      },
1009      "outputs": [
1010       {
1011        "output_type": "stream",
1012        "stream": "stdout",
1013        "text": [
1014         "std dev before and after: 4.61383319712 4.61383319712\n"
1015        ]
1016       }
1017      ],
1018      "prompt_number": 19
1019     },
1020     {
1021      "cell_type": "markdown",
1022      "metadata": {
1023       "cell_tags": []
1024      },
1025      "source": [
1026       "Those values look the same,\n",
1027       "but we probably wouldn't notice if they were different in the sixth decimal place.\n",
1028       "Let's do this instead:"
1029      ]
1030     },
1031     {
1032      "cell_type": "code",
1033      "collapsed": false,
1034      "input": [
1035       "print 'difference in standard deviations before and after:', data.std() - centered.std()"
1036      ],
1037      "language": "python",
1038      "metadata": {
1039       "cell_tags": []
1040      },
1041      "outputs": [
1042       {
1043        "output_type": "stream",
1044        "stream": "stdout",
1045        "text": [
1046         "difference in standard deviations before and after: -3.5527136788e-15\n"
1047        ]
1048       }
1049      ],
1050      "prompt_number": 20
1051     },
1052     {
1053      "cell_type": "markdown",
1054      "metadata": {
1055       "cell_tags": []
1056      },
1057      "source": [
1058       "Again,\n",
1059       "the difference is very small.\n",
1060       "It's still possible that our function is wrong,\n",
1061       "but it seems unlikely enough that we should probably get back to doing our analysis.\n",
1062       "We have one more task first, though:\n",
1063       "we should write some [documentation](../../gloss.html#documentation) for our function\n",
1064       "to remind ourselves later what it's for and how to use it.\n",
1065       "\n",
1066       "The usual way to put documentation in software is to add [comments](../../gloss.html#comment) like this:"
1067      ]
1068     },
1069     {
1070      "cell_type": "code",
1071      "collapsed": false,
1072      "input": [
1073       "# center(data, desired): return a new array containing the original data centered around the desired value.\n",
1074       "def center(data, desired):\n",
1075       "    return (data - data.mean()) + desired"
1076      ],
1077      "language": "python",
1078      "metadata": {
1079       "cell_tags": []
1080      },
1081      "outputs": [],
1082      "prompt_number": 21
1083     },
1084     {
1085      "cell_type": "markdown",
1086      "metadata": {
1087       "cell_tags": []
1088      },
1089      "source": [
1090       "There's a better way, though.\n",
1091       "If the first thing in a function is a string that isn't assigned to a variable,\n",
1092       "that string is attached to the function as its documentation:"
1093      ]
1094     },
1095     {
1096      "cell_type": "code",
1097      "collapsed": false,
1098      "input": [
1099       "def center(data, desired):\n",
1100       "    '''Return a new array containing the original data centered around the desired value.'''\n",
1101       "    return (data - data.mean()) + desired"
1102      ],
1103      "language": "python",
1104      "metadata": {
1105       "cell_tags": []
1106      },
1107      "outputs": [],
1108      "prompt_number": 1
1109     },
1110     {
1111      "cell_type": "markdown",
1112      "metadata": {
1113       "cell_tags": []
1114      },
1115      "source": [
1116       "This is better because we can now ask Python's built-in help system to show us the documentation for the function:"
1117      ]
1118     },
1119     {
1120      "cell_type": "code",
1121      "collapsed": false,
1122      "input": [
1123       "help(center)"
1124      ],
1125      "language": "python",
1126      "metadata": {
1127       "cell_tags": []
1128      },
1129      "outputs": [
1130       {
1131        "output_type": "stream",
1132        "stream": "stdout",
1133        "text": [
1134         "Help on function center in module __main__:\n",
1135         "\n",
1136         "center(data, desired)\n",
1137         "    Return a new array containing the original data centered around the desired value.\n",
1138         "\n"
1139        ]
1140       }
1141      ],
1142      "prompt_number": 23
1143     },
1144     {
1145      "cell_type": "markdown",
1146      "metadata": {
1147       "cell_tags": []
1148      },
1149      "source": [
1150       "A string like this is called a [docstring](../../gloss.html#docstring).\n",
1151       "We don't need to use triple quotes when we write one,\n",
1152       "but if we do,\n",
1153       "we can break the string across multiple lines:"
1154      ]
1155     },
1156     {
1157      "cell_type": "code",
1158      "collapsed": false,
1159      "input": [
1160       "def center(data, desired):\n",
1161       "    '''Return a new array containing the original data centered around the desired value.\n",
1162       "    Example: center([1, 2, 3], 0) => [-1, 0, 1]'''\n",
1163       "    return (data - data.mean()) + desired\n",
1164       "\n",
1165       "help(center)"
1166      ],
1167      "language": "python",
1168      "metadata": {
1169       "cell_tags": []
1170      },
1171      "outputs": [
1172       {
1173        "output_type": "stream",
1174        "stream": "stdout",
1175        "text": [
1176         "Help on function center in module __main__:\n",
1177         "\n",
1178         "center(data, desired)\n",
1179         "    Return a new array containing the original data centered around the desired value.\n",
1180         "    Example: center([1, 2, 3], 0) => [-1, 0, 1]\n",
1181         "\n"
1182        ]
1183       }
1184      ],
1185      "prompt_number": 24
1186     },
1187     {
1188      "cell_type": "markdown",
1189      "metadata": {
1190       "cell_tags": [
1191        "challenges"
1192       ]
1193      },
1194      "source": [
1195       "#### Challenges\n",
1196       "\n",
1197       "1.  Write a function called `analyze` that takes a filename as a parameter\n",
1198       "    and displays the three graphs produced in the [previous lesson](01-numpy.ipynb),\n",
1199       "    i.e.,\n",
1200       "    `analyze('inflammation-01.csv')` should produce the graphs already shown,\n",
1201       "    while `analyze('inflammation-02.csv')` should produce corresponding graphs for the second data set.\n",
1202       "    Be sure to give your function a docstring.\n",
1203       "\n",
1204       "2.  Write a function `rescale` that takes an array as input\n",
1205       "    and returns a corresponding array of values scaled to lie in the range 0.0 to 1.0.\n",
1206       "    (If $L$ and $H$ are the lowest and highest values in the original array,\n",
1207       "    then the replacement for a value $v$ should be $(v-L) / (H-L)$.)\n",
1208       "    Be sure to give the function a docstring.\n",
1209       "\n",
1210       "3.  Run the commands `help(numpy.arange)` and `help(numpy.linspace)`\n",
1211       "    to see how to use these functions to generate regularly-spaced values,\n",
1212       "    then use those values to test your `rescale` function."
1213      ]
1214     },
1215     {
1216      "cell_type": "heading",
1217      "level": 3,
1218      "metadata": {
1219       "cell_tags": []
1220      },
1221      "source": [
1222       "Defining Defaults"
1223      ]
1224     },
1225     {
1226      "cell_type": "markdown",
1227      "metadata": {
1228       "cell_tags": []
1229      },
1230      "source": [
1231       "We have passed parameters to functions in two ways:\n",
1232       "directly, as in `span(data)`,\n",
1233       "and by name, as in `numpy.loadtxt(fname='something.csv', delimiter=',')`.\n",
1234       "In fact,\n",
1235       "we can pass the filename to `loadtxt` without the `fname=`:"
1236      ]
1237     },
1238     {
1239      "cell_type": "code",
1240      "collapsed": false,
1241      "input": [
1242       "numpy.loadtxt('inflammation-01.csv', delimiter=',')"
1243      ],
1244      "language": "python",
1245      "metadata": {
1246       "cell_tags": []
1247      },
1248      "outputs": [
1249       {
1250        "metadata": {},
1251        "output_type": "pyout",
1252        "prompt_number": 25,
1253        "text": [
1254         "array([[ 0.,  0.,  1., ...,  3.,  0.,  0.],\n",
1255         "       [ 0.,  1.,  2., ...,  1.,  0.,  1.],\n",
1256         "       [ 0.,  1.,  1., ...,  2.,  1.,  1.],\n",
1257         "       ..., \n",
1258         "       [ 0.,  1.,  1., ...,  1.,  1.,  1.],\n",
1259         "       [ 0.,  0.,  0., ...,  0.,  2.,  0.],\n",
1260         "       [ 0.,  0.,  1., ...,  1.,  1.,  0.]])"
1261        ]
1262       }
1263      ],
1264      "prompt_number": 25
1265     },
1266     {
1267      "cell_type": "markdown",
1268      "metadata": {
1269       "cell_tags": []
1270      },
1271      "source": [
1272       "but we still need to say `delimiter=`:"
1273      ]
1274     },
1275     {
1276      "cell_type": "code",
1277      "collapsed": false,
1278      "input": [
1279       "numpy.loadtxt('inflammation-01.csv', ',')"
1280      ],
1281      "language": "python",
1282      "metadata": {
1283       "cell_tags": []
1284      },
1285      "outputs": [
1286       {
1287        "ename": "TypeError",
1288        "evalue": "data type \",\" not understood",
1289        "output_type": "pyerr",
1290        "traceback": [
1291         "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
1292         "\u001b[0;32m<ipython-input-26-e3bc6cf4fd6a>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnumpy\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mloadtxt\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'inflammation-01.csv'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m','\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
1293         "\u001b[0;32m/Users/gwilson/anaconda/lib/python2.7/site-packages/numpy/lib/npyio.pyc\u001b[0m in \u001b[0;36mloadtxt\u001b[0;34m(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin)\u001b[0m\n\u001b[1;32m    775\u001b[0m     \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    776\u001b[0m         \u001b[0;31m# Make sure we're dealing with a proper dtype\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 777\u001b[0;31m         \u001b[0mdtype\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdtype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdtype\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    778\u001b[0m         \u001b[0mdefconv\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_getconv\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdtype\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    779\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
1294         "\u001b[0;31mTypeError\u001b[0m: data type \",\" not understood"
1295        ]
1296       }
1297      ],
1298      "prompt_number": 26
1299     },
1300     {
1301      "cell_type": "markdown",
1302      "metadata": {
1303       "cell_tags": []
1304      },
1305      "source": [
1306       "To understand what's going on,\n",
1307       "and make our own functions easier to use,\n",
1308       "let's re-define our `center` function like this:"
1309      ]
1310     },
1311     {
1312      "cell_type": "code",
1313      "collapsed": false,
1314      "input": [
1315       "def center(data, desired=0.0):\n",
1316       "    '''Return a new array containing the original data centered around the desired value (0 by default).\n",
1317       "    Example: center([1, 2, 3], 0) => [-1, 0, 1]'''\n",
1318       "    return (data - data.mean()) + desired"
1319      ],
1320      "language": "python",
1321      "metadata": {
1322       "cell_tags": []
1323      },
1324      "outputs": [],
1325      "prompt_number": 27
1326     },
1327     {
1328      "cell_type": "markdown",
1329      "metadata": {
1330       "cell_tags": []
1331      },
1332      "source": [
1333       "The key change is that the second parameter is now written `desired=0.0` instead of just `desired`.\n",
1334       "If we call the function with two arguments,\n",
1335       "it works as it did before:"
1336      ]
1337     },
1338     {
1339      "cell_type": "code",
1340      "collapsed": false,
1341      "input": [
1342       "test_data = numpy.zeros((2, 2))\n",
1343       "print center(test_data, 3)"
1344      ],
1345      "language": "python",
1346      "metadata": {
1347       "cell_tags": []
1348      },
1349      "outputs": [
1350       {
1351        "output_type": "stream",
1352        "stream": "stdout",
1353        "text": [
1354         "[[ 3.  3.]\n",
1355         " [ 3.  3.]]\n"
1356        ]
1357       }
1358      ],
1359      "prompt_number": 28
1360     },
1361     {
1362      "cell_type": "markdown",
1363      "metadata": {
1364       "cell_tags": []
1365      },
1366      "source": [
1367       "But we can also now call it with just one parameter,\n",
1368       "in which case `desired` is automatically assigned the [default value](../../gloss.html#default-parameter-value) of 0.0:"
1369      ]
1370     },
1371     {
1372      "cell_type": "code",
1373      "collapsed": false,
1374      "input": [
1375       "more_data = 5 + numpy.zeros((2, 2))\n",
1376       "print 'data before centering:', more_data\n",
1377       "print 'centered data:', center(more_data)"
1378      ],
1379      "language": "python",
1380      "metadata": {
1381       "cell_tags": []
1382      },
1383      "outputs": [
1384       {
1385        "output_type": "stream",
1386        "stream": "stdout",
1387        "text": [
1388         "data before centering: [[ 5.  5.]\n",
1389         " [ 5.  5.]]\n",
1390         "centered data: [[ 0.  0.]\n",
1391         " [ 0.  0.]]\n"
1392        ]
1393       }
1394      ],
1395      "prompt_number": 29
1396     },
1397     {
1398      "cell_type": "markdown",
1399      "metadata": {
1400       "cell_tags": []
1401      },
1402      "source": [
1403       "This is handy:\n",
1404       "if we usually want a function to work one way,\n",
1405       "but occasionally need it to do something else,\n",
1406       "we can allow people to pass a parameter when they need to\n",
1407       "but provide a default to make the normal case easier.\n",
1408       "The example below shows how Python matches values to parameters:"
1409      ]
1410     },
1411     {
1412      "cell_type": "code",
1413      "collapsed": false,
1414      "input": [
1415       "def display(a=1, b=2, c=3):\n",
1416       "    print 'a:', a, 'b:', b, 'c:', c\n",
1417       "\n",
1418       "print 'no parameters:'\n",
1419       "display()\n",
1420       "print 'one parameter:'\n",
1421       "display(55)\n",
1422       "print 'two parameters:'\n",
1423       "display(55, 66)"
1424      ],
1425      "language": "python",
1426      "metadata": {
1427       "cell_tags": []
1428      },
1429      "outputs": [
1430       {
1431        "output_type": "stream",
1432        "stream": "stdout",
1433        "text": [
1434         "no parameters:\n",
1435         "a: 1 b: 2 c: 3\n",
1436         "one parameter:\n",
1437         "a: 55 b: 2 c: 3\n",
1438         "two parameters:\n",
1439         "a: 55 b: 66 c: 3\n"
1440        ]
1441       }
1442      ],
1443      "prompt_number": 30
1444     },
1445     {
1446      "cell_type": "markdown",
1447      "metadata": {
1448       "cell_tags": []
1449      },
1450      "source": [
1451       "As this example shows,\n",
1452       "parameters are matched up from left to right,\n",
1453       "and any that haven't been given a value explicitly get their default value.\n",
1454       "We can override this behavior by naming the value as we pass it in:"
1455      ]
1456     },
1457     {
1458      "cell_type": "code",
1459      "collapsed": false,
1460      "input": [
1461       "print 'only setting the value of c'\n",
1462       "display(c=77)"
1463      ],
1464      "language": "python",
1465      "metadata": {
1466       "cell_tags": []
1467      },
1468      "outputs": [
1469       {
1470        "output_type": "stream",
1471        "stream": "stdout",
1472        "text": [
1473         "only setting the value of c\n",
1474         "a: 1 b: 2 c: 77\n"
1475        ]
1476       }
1477      ],
1478      "prompt_number": 31
1479     },
1480     {
1481      "cell_type": "markdown",
1482      "metadata": {
1483       "cell_tags": []
1484      },
1485      "source": [
1486       "With that in hand,\n",
1487       "let's look at the help for `numpy.loadtxt`:"
1488      ]
1489     },
1490     {
1491      "cell_type": "code",
1492      "collapsed": false,
1493      "input": [
1494       "help(numpy.loadtxt)"
1495      ],
1496      "language": "python",
1497      "metadata": {
1498       "cell_tags": []
1499      },
1500      "outputs": [
1501       {
1502        "output_type": "stream",
1503        "stream": "stdout",
1504        "text": [
1505         "Help on function loadtxt in module numpy.lib.npyio:\n",
1506         "\n",
1507         "loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)\n",
1508         "    Load data from a text file.\n",
1509         "    \n",
1510         "    Each row in the text file must have the same number of values.\n",
1511         "    \n",
1512         "    Parameters\n",
1513         "    ----------\n",
1514         "    fname : file or str\n",
1515         "        File, filename, or generator to read.  If the filename extension is\n",
1516         "        ``.gz`` or ``.bz2``, the file is first decompressed. Note that\n",
1517         "        generators should return byte strings for Python 3k.\n",
1518         "    dtype : data-type, optional\n",
1519         "        Data-type of the resulting array; default: float.  If this is a\n",
1520         "        record data-type, the resulting array will be 1-dimensional, and\n",
1521         "        each row will be interpreted as an element of the array.  In this\n",
1522         "        case, the number of columns used must match the number of fields in\n",
1523         "        the data-type.\n",
1524         "    comments : str, optional\n",
1525         "        The character used to indicate the start of a comment;\n",
1526         "        default: '#'.\n",
1527         "    delimiter : str, optional\n",
1528         "        The string used to separate values.  By default, this is any\n",
1529         "        whitespace.\n",
1530         "    converters : dict, optional\n",
1531         "        A dictionary mapping column number to a function that will convert\n",
1532         "        that column to a float.  E.g., if column 0 is a date string:\n",
1533         "        ``converters = {0: datestr2num}``.  Converters can also be used to\n",
1534         "        provide a default value for missing data (but see also `genfromtxt`):\n",
1535         "        ``converters = {3: lambda s: float(s.strip() or 0)}``.  Default: None.\n",
1536         "    skiprows : int, optional\n",
1537         "        Skip the first `skiprows` lines; default: 0.\n",
1538         "    usecols : sequence, optional\n",
1539         "        Which columns to read, with 0 being the first.  For example,\n",
1540         "        ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.\n",
1541         "        The default, None, results in all columns being read.\n",
1542         "    unpack : bool, optional\n",
1543         "        If True, the returned array is transposed, so that arguments may be\n",
1544         "        unpacked using ``x, y, z = loadtxt(...)``.  When used with a record\n",
1545         "        data-type, arrays are returned for each field.  Default is False.\n",
1546         "    ndmin : int, optional\n",
1547         "        The returned array will have at least `ndmin` dimensions.\n",
1548         "        Otherwise mono-dimensional axes will be squeezed.\n",
1549         "        Legal values: 0 (default), 1 or 2.\n",
1550         "        .. versionadded:: 1.6.0\n",
1551         "    \n",
1552         "    Returns\n",
1553         "    -------\n",
1554         "    out : ndarray\n",
1555         "        Data read from the text file.\n",
1556         "    \n",
1557         "    See Also\n",
1558         "    --------\n",
1559         "    load, fromstring, fromregex\n",
1560         "    genfromtxt : Load data with missing values handled as specified.\n",
1561         "    scipy.io.loadmat : reads MATLAB data files\n",
1562         "    \n",
1563         "    Notes\n",
1564         "    -----\n",
1565         "    This function aims to be a fast reader for simply formatted files.  The\n",
1566         "    `genfromtxt` function provides more sophisticated handling of, e.g.,\n",
1567         "    lines with missing values.\n",
1568         "    \n",
1569         "    Examples\n",
1570         "    --------\n",
1571         "    >>> from StringIO import StringIO   # StringIO behaves like a file object\n",
1572         "    >>> c = StringIO(\"0 1\\n2 3\")\n",
1573         "    >>> np.loadtxt(c)\n",
1574         "    array([[ 0.,  1.],\n",
1575         "           [ 2.,  3.]])\n",
1576         "    \n",
1577         "    >>> d = StringIO(\"M 21 72\\nF 35 58\")\n",
1578         "    >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),\n",
1579         "    ...                      'formats': ('S1', 'i4', 'f4')})\n",
1580         "    array([('M', 21, 72.0), ('F', 35, 58.0)],\n",
1581         "          dtype=[('gender', '|S1'), ('age', '<i4'), ('weight', '<f4')])\n",
1582         "    \n",
1583         "    >>> c = StringIO(\"1,0,2\\n3,0,4\")\n",
1584         "    >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)\n",
1585         "    >>> x\n",
1586         "    array([ 1.,  3.])\n",
1587         "    >>> y\n",
1588         "    array([ 2.,  4.])\n",
1589         "\n"
1590        ]
1591       }
1592      ],
1593      "prompt_number": 32
1594     },
1595     {
1596      "cell_type": "markdown",
1597      "metadata": {
1598       "cell_tags": []
1599      },
1600      "source": [
1601       "There's a lot of information here,\n",
1602       "but the most important part is the first couple of lines:\n",
1603       "\n",
1604       "~~~python\n",
1605       "loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None,\n",
1606       "        unpack=False, ndmin=0)\n",
1607       "~~~\n",
1608       "\n",
1609       "This tells us that `loadtxt` has one parameter called `fname` that doesn't have a default value,\n",
1610       "and eight others that do.\n",
1611       "If we call the function like this:\n",
1612       "\n",
1613       "~~~python\n",
1614       "numpy.loadtxt('inflammation-01.csv', ',')\n",
1615       "~~~\n",
1616       "\n",
1617       "then the filename is assigned to `fname` (which is what we want),\n",
1618       "but the delimiter string `','` is assigned to `dtype` rather than `delimiter`,\n",
1619       "because `dtype` is the second parameter in the list.\n",
1620       "That's why we don't have to provide `fname=` for the filename,\n",
1621       "but *do* have to provide `delimiter=` for the second parameter."
1622      ]
1623     },
1624     {
1625      "cell_type": "markdown",
1626      "metadata": {
1627       "cell_tags": [
1628        "challenges"
1629       ]
1630      },
1631      "source": [
1632       "#### Challenges\n",
1633       "\n",
1634       "1.  Rewrite the `normalize` function so that it scales data to lie between 0.0 and 1.0 by default,\n",
1635       "    but will allow the caller to specify lower and upper bounds if they want.\n",
1636       "    Compare your implementation to your neighbor's:\n",
1637       "    do the two functions always behave the same way?"
1638      ]
1639     },
1640     {
1641      "cell_type": "markdown",
1642      "metadata": {
1643       "cell_tags": [
1644        "keypoints"
1645       ]
1646      },
1647      "source": [
1648       "#### Key Points\n",
1649       "\n",
1650       "*   Define a function using `def name(...params...)`.\n",
1651       "*   The body of a function must be indented.\n",
1652       "*   Call a function using `name(...values...)`.\n",
1653       "*   Numbers are stored as integers or floating-point numbers.\n",
1654       "*   Integer division produces the whole part of the answer (not the fractional part).\n",
1655       "*   Each time a function is called, a new stack frame is created on the [call stack](../../gloss.html#call-stack) to hold its parameters and local variables.\n",
1656       "*   Python looks for variables in the current stack frame before looking for them at the top level.\n",
1657       "*   Use `help(thing)` to view help for something.\n",
1658       "*   Put docstrings in functions to provide help for that function.\n",
1659       "*   Specify default values for parameters when defining a function using `name=value` in the parameter list.\n",
1660       "*   Parameters can be passed by matching based on name, by position, or by omitting them (in which case the default value is used)."
1661      ]
1662     },
1663     {
1664      "cell_type": "markdown",
1665      "metadata": {
1666       "cell_tags": []
1667      },
1668      "source": [
1669       "#### Next Steps\n",
1670       "\n",
1671       "We now have a function called `analyze` to visualize a single data set.\n",
1672       "We could use it to explore all 12 of our current data sets like this:\n",
1673       "\n",
1674       "~~~python\n",
1675       "analyze('inflammation-01.csv')\n",
1676       "analyze('inflammation-02.csv')\n",
1677       "...\n",
1678       "analyze('inflammation-12.csv')\n",
1679       "~~~\n",
1680       "\n",
1681       "but the chances of us typing all 12 filenames correctly aren't great,\n",
1682       "and we'll be even worse off if we get another hundred files.\n",
1683       "What we need is a way to tell Python to do something once for each file,\n",
1684       "and that will be the subject of the next lesson."
1685      ]
1686     }
1687    ],
1688    "metadata": {}
1689   }
1690  ]
1691 }