Imported all the notebooks
[tm351-notebooks.git] / notebooks / 01. Bootcamp notebooks / 01.4 Defining new functions in python.ipynb
1 {
2 "metadata": {
3 "name": "",
4 "signature": "sha256:0f8a2df206d65d4e719933b19d6f9a54b9c850b4fd9967d46202aee32703cf62"
5 },
6 "nbformat": 3,
7 "nbformat_minor": 0,
8 "worksheets": [
9 {
10 "cells": [
11 {
12 "cell_type": "heading",
13 "level": 2,
14 "metadata": {},
15 "source": [
16 "Control Flow"
17 ]
18 },
19 {
20 "cell_type": "markdown",
21 "metadata": {},
22 "source": [
23 "We have already seen elements of control flow, such as for loops for iterating through list memberships, or conditional statements as used in the if/else ternary statement or as part of a list comprehension. Here's a quick recap:"
24 ]
25 },
26 {
27 "cell_type": "code",
28 "collapsed": false,
29 "input": [
30 "#Iterate through a list\n",
31 "#The , after the print statement prevents the printing of a new line character; further print outputs will appear on the same line\n",
32 "for x in ['this', 'that', 'the other']:\n",
33 " print(x),\n",
34 "print('')\n",
35 "\n",
36 "#Iterate through a range of numbers\n",
37 "for x in range(3): print(x),"
38 ],
39 "language": "python",
40 "metadata": {},
41 "outputs": []
42 },
43 {
44 "cell_type": "code",
45 "collapsed": false,
46 "input": [
47 "#Ranges can also be more elaborate - as with list indices, wath the upper fencepost\n",
48 "for x in range(2,4): print(x),\n",
49 "print('')\n",
50 "\n",
51 "#Add a step\n",
52 "for x in range(10,15, 2): print(x),"
53 ],
54 "language": "python",
55 "metadata": {},
56 "outputs": []
57 },
58 {
59 "cell_type": "code",
60 "collapsed": false,
61 "input": [
62 "#Conditionals..\n",
63 "\n",
64 "#First set variables a and b to the same value\n",
65 "a=b=4\n",
66 "\n",
67 "#Test a condition and act if true\n",
68 "if a>b:\n",
69 " print('bigger')\n",
70 "\n",
71 "#Test a condition and act one way or another depending on the result\n",
72 "if a>b:\n",
73 " print('bigger')\n",
74 "else:\n",
75 " print('smaller')\n",
76 "\n",
77 "#If you think you need an else but don't know what to do there yet, pass\n",
78 "if a>b:\n",
79 " print('bigger')\n",
80 "else:\n",
81 " #erm - what do I do here?\n",
82 " pass\n",
83 " \n",
84 "#Test over multiple conditions\n",
85 "if a>b:\n",
86 " print('bigger')\n",
87 "elif a<b:\n",
88 " print('smaller')\n",
89 "else:\n",
90 " print('same')\n",
91 "\n",
92 "#Nest tests\n",
93 "if a!=b:\n",
94 " if a>b:\n",
95 " print('bigger')\n",
96 " else:\n",
97 " print('smaller')\n",
98 "else:\n",
99 " print('same')"
100 ],
101 "language": "python",
102 "metadata": {},
103 "outputs": []
104 },
105 {
106 "cell_type": "code",
107 "collapsed": false,
108 "input": [
109 "#Looped conditionals\n",
110 "a=1\n",
111 "while a<5:\n",
112 " print(a),\n",
113 " a+=1\n",
114 "print('Done')\n",
115 "\n",
116 "#We can also break out of a loop\n",
117 "while a<10:\n",
118 " print(a),\n",
119 " a+=1\n",
120 " if a==8:\n",
121 " break\n",
122 "print('Done')\n",
123 "\n",
124 "#Or we can skip an item by breaking out of a loop and continuing with its next iteration\n",
125 "while a<15:\n",
126 " if a==12:\n",
127 " a+=1\n",
128 " continue\n",
129 " print(a),\n",
130 " a+=1\n",
131 "\n",
132 "print('Done')"
133 ],
134 "language": "python",
135 "metadata": {},
136 "outputs": []
137 },
138 {
139 "cell_type": "code",
140 "collapsed": false,
141 "input": [
142 "#Wrapping statements in a try/except handler will attempt to execute the statements in the try block.\n",
143 "#If an error is raised, the code execution passes to the excpet block BUT WITHOUT ROLLBACK.\n",
144 "try:\n",
145 " 1+'one'\n",
146 "except:\n",
147 " print('oops')"
148 ],
149 "language": "python",
150 "metadata": {},
151 "outputs": []
152 },
153 {
154 "cell_type": "code",
155 "collapsed": false,
156 "input": [
157 "a=1\n",
158 "try:\n",
159 " a=2\n",
160 " b=a+'sr'\n",
161 "except:\n",
162 " pass\n",
163 "a"
164 ],
165 "language": "python",
166 "metadata": {},
167 "outputs": []
168 },
169 {
170 "cell_type": "markdown",
171 "metadata": {},
172 "source": [
173 "*You need to be mindful the white space...* The white space used to create indentations within a block is significant. The amount of whitespace used at a particular level of nesting needs to be kept constant within a block.\n",
174 "\n",
175 "The IPython notebook code cells are sensitive to code level, and will try to set indentation approriately. \n",
176 "\n",
177 "<img style=\"float:left; padding-right:5px;\" src=\"files/images/r_arrow.png\"/> Insert a code cell below and try to write simple *while* loop that will print out the numbers 1 to 5, noticing what action the editor takes when you enter the *while* block."
178 ]
179 },
180 {
181 "cell_type": "heading",
182 "level": 2,
183 "metadata": {},
184 "source": [
185 "Chunking your Code - functions"
186 ]
187 },
188 {
189 "cell_type": "code",
190 "collapsed": false,
191 "input": [
192 "#functions let you strucutre your code in convenient ways\n",
193 "def compare(a,b):\n",
194 " comp='same'\n",
195 " if a>b:\n",
196 " comp='bigger'\n",
197 " elif a<b:\n",
198 " comp='smaller'\n",
199 " return comp\n",
200 "\n",
201 "print( compare(7,8) )"
202 ],
203 "language": "python",
204 "metadata": {},
205 "outputs": []
206 },
207 {
208 "cell_type": "code",
209 "collapsed": false,
210 "input": [
211 "#The function is defined in the IPython session so it can be called across notebook cells\n",
212 "print( compare(3,3) )\n",
213 "print( compare(2,1) )"
214 ],
215 "language": "python",
216 "metadata": {},
217 "outputs": []
218 },
219 {
220 "cell_type": "code",
221 "collapsed": false,
222 "input": [
223 "#We can call functions from other functions\n",
224 "def compare2(a,b):\n",
225 " return \"{0} is {1} than {2}\".format( a, compare(a,b), b)\n",
226 "\n",
227 "print( compare2(3,5) )"
228 ],
229 "language": "python",
230 "metadata": {},
231 "outputs": []
232 },
233 {
234 "cell_type": "code",
235 "collapsed": false,
236 "input": [
237 "#We can return multiple values from a function as a tuple\n",
238 "def compare3(a,b):\n",
239 " return a-b, compare2(a,b)\n",
240 "\n",
241 "compare3(5,8)"
242 ],
243 "language": "python",
244 "metadata": {},
245 "outputs": []
246 },
247 {
248 "cell_type": "code",
249 "collapsed": false,
250 "input": [
251 "#We can pass those returned values into separate variables\n",
252 "x, y = compare3(5,8)\n",
253 "print(y)"
254 ],
255 "language": "python",
256 "metadata": {},
257 "outputs": []
258 },
259 {
260 "cell_type": "code",
261 "collapsed": false,
262 "input": [
263 "#Take care when passing lists into functions - they are passed by value\n",
264 "def passByVal_listTest(l):\n",
265 " l.append('just added')\n",
266 "\n",
267 "l1= ['this', 'that']\n",
268 "l2=l1\n",
269 "l3=list(l1)\n",
270 "\n",
271 "passByVal_listTest(l1)\n",
272 "\n",
273 "print(l1)\n",
274 "print(l2)\n",
275 "print(l3)"
276 ],
277 "language": "python",
278 "metadata": {},
279 "outputs": []
280 },
281 {
282 "cell_type": "code",
283 "collapsed": false,
284 "input": [
285 "#The scalar types are passed into functions by value\n",
286 "def passByVal_intTest(i):\n",
287 " i=i+1\n",
288 " return i\n",
289 "\n",
290 "j=5\n",
291 "passByVal_intTest(j)\n",
292 "print(j)\n",
293 "print( passByVal_intTest(j) )\n",
294 "\n",
295 "#Test with a string\n",
296 "def passByVal_strTest(s):\n",
297 " s=s+'added'\n",
298 " return s\n",
299 "\n",
300 "q=\"example string\"\n",
301 "passByVal_strTest(q)\n",
302 "print(q)\n",
303 "q= passByVal_strTest(q)\n",
304 "print( q ) \n"
305 ],
306 "language": "python",
307 "metadata": {},
308 "outputs": []
309 },
310 {
311 "cell_type": "code",
312 "collapsed": false,
313 "input": [
314 "#What do you think will happen with a dict?\n",
315 "def passByVal_dictTest(d):\n",
316 " d['added']='item'\n",
317 "\n",
318 "d1={'this':'that'}\n",
319 "d2=d1\n",
320 "d3=d1.copy()\n",
321 "passByVal_dictTest(d2)\n",
322 "\n",
323 "print(d1)\n",
324 "print(d2)\n",
325 "print(d3)"
326 ],
327 "language": "python",
328 "metadata": {},
329 "outputs": []
330 },
331 {
332 "cell_type": "code",
333 "collapsed": false,
334 "input": [
335 "#Anonymous functions, also called lambda functions, can be thought of as \"headless\" \n",
336 "y = lambda x: x*x\n",
337 "print( y(5) )\n",
338 "\n",
339 "#We would typically define and call a function as follows\n",
340 "def notHeadless(x):\n",
341 " return x*x\n",
342 "print( notHeadless(5) )\n",
343 "\n",
344 "#Here's an anonymous equivalent defined \"on the fly\"\n",
345 "(lambda x: x^2)(4)"
346 ],
347 "language": "python",
348 "metadata": {},
349 "outputs": []
350 },
351 {
352 "cell_type": "heading",
353 "level": 2,
354 "metadata": {},
355 "source": [
356 "Importing Libraries"
357 ]
358 },
359 {
360 "cell_type": "code",
361 "collapsed": false,
362 "input": [
363 "#And finally, we can of course import Python libraries\n",
364 "import datetime"
365 ],
366 "language": "python",
367 "metadata": {},
368 "outputs": []
369 },
370 {
371 "cell_type": "code",
372 "collapsed": false,
373 "input": [
374 "#And make use of their contents in other cells...\n",
375 "datetime.datetime.now()"
376 ],
377 "language": "python",
378 "metadata": {},
379 "outputs": []
380 },
381 {
382 "cell_type": "code",
383 "collapsed": false,
384 "input": [
385 "#We can also import packages from packages, and rename them with a convenience name\n",
386 "import datetime as dt1\n",
387 "print ( dt1.datetime.now() )\n",
388 "\n",
389 "from datetime import datetime as dt2\n",
390 "print( dt2.now() )"
391 ],
392 "language": "python",
393 "metadata": {},
394 "outputs": []
395 },
396 {
397 "cell_type": "heading",
398 "level": 3,
399 "metadata": {},
400 "source": [
401 "Installing New Libraries"
402 ]
403 },
404 {
405 "cell_type": "markdown",
406 "metadata": {},
407 "source": [
408 "If you want to install additional Python libraries, use the `pip3` installer via a shell command (for example `!pip3 install NEWPACKAGE`).\n",
409 "\n",
410 "You can also install packages from github repositories using commands of the form `!pip3 install git+https://github.com/tbicr/folium.git@fixed#folium` ."
411 ]
412 },
413 {
414 "cell_type": "heading",
415 "level": 2,
416 "metadata": {},
417 "source": [
418 "What Next?"
419 ]
420 },
421 {
422 "cell_type": "markdown",
423 "metadata": {},
424 "source": [
425 "If you are working through this notebook as part of an inline exercise, return to the course materials now.\n",
426 "\n",
427 "If you are working through this set of notebooks as a whole, move on to the next step in the bootcamp: [01.5 Python file handling](01.5%20Python%20file%20handling.ipynb)"
428 ]
429 }
430 ],
431 "metadata": {}
432 }
433 ]
434 }