forked from calebsmith/gdi-intro-python
-
Notifications
You must be signed in to change notification settings - Fork 1
/
class3.html
565 lines (484 loc) · 24.8 KB
/
class3.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Intro to Python ~ Girl Develop It</title>
<meta name="description" content="This is the official Girl Develop It Core Intro to Python course. The course is meant to be taught in four two-hour sessions. Each of the slides and practice files are customizable according to the needs of a given class or audience.">
<meta name="author" content="Girl Develop It">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<link rel="stylesheet" href="reveal/css/reveal.css">
<link rel="stylesheet" href="reveal/css/theme/gdicool.css" id="theme">
<!-- For syntax highlighting -->
<!-- light editor<link rel="stylesheet" href="lib/css/light.css">-->
<!-- dark editor--><link rel="stylesheet" href="reveal/lib/css/dark.css">
<!-- If use the PDF print sheet so students can print slides-->
<link rel="stylesheet" href="reveal/css/print/pdf.css" type="text/css" media="print">
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<!-- Opening slide -->
<section>
<img src="images/gdi_logo_badge.png">
<h3>Intro to Python</h3>
<h4>Class 3</h3>
</section>
<!-- Block 1 25 minutes -->
<section>
<h3>Review</h3>
<ul>
<li>Functions - calls, definitions, returns, arguments</li>
<li>Conditions - if, elif, else</li>
<li>Loops - while, for</li>
</ul>
</section>
<section>
<h3>What we will cover today</h3>
<ul>
<li class="fragment">More Functions</li>
<li class="fragment">Method calls</li>
<li class="fragment">Lists and dictionaries</li>
<li class="fragment">Python builtin functions</li>
</ul>
</section>
<section>
<h3>More with Functions</h3>
<p>Functions can also call other functions.</p>
<p class="fragment">One can use this to break up tasks into small pieces that rely on others to do their work.</p>
<pre><code contenteditable class="fragment python">
from math import sqrt
def absolute_difference(value_a, value_b):
return abs(value_a - value_b)
def find_width_height(x1, y1, x2, y2):
width = absolute_difference(x1, x2)
height = absolute_difference(y1, y2)
return width, height
def get_hypotenuse(a, b):
return sqrt(a ** 2 + b ** 2)
def get_area_rectangle(width, height):
return width * height
def print_area_and_hypotenuse(x1, y1, x2, y2):
width, height = find_width_height(x1, y1, x2, y2)
area = get_area_rectangle(width, height)
hypotenuse = get_hypotenuse(width, height)
print('Area of the rectangle is:')
print(area)
print('The diagonal of the rectangle is:')
print(hypotenuse)
</code></pre>
</section>
<section>
<h3>Function Composition</h3>
<p><strong>Function composition</strong> is when the output of one function acts as the input of another</p>
<pre><code contenteditable class="fragment python">
from math import sqrt
def find_width_height(x1, y1, x2, y2):
return abs(x1 - x2), abs(y1 - y2)
def get_hypotenuse(a, b):
return sqrt(a ** 2 + b ** 2)
def print_hypotenuse(x1, y1, x2, y2):
print('The diagonal of the rectangle is:')
print(get_hypotenuse(find_width_height(x1, y1, x2, y2)))
# f(g(x))
# is the same as:
# y = g(x)
# f(y)
</code></pre>
</section>
<section>
<h3>Method Calls</h3>
<p>Remember: Functions are called by their name - `my_function()` - can be passed data in the form of parameters - `my_function(my_parameter)` and usually return some sort of value. This all happens explicitly.</p>
<p><strong>Methods</strong> meanwhile, are also called by name but they are associated with an object. Really, they are identical to functions except that the data passed into it is passed implicitly.</p>
<p class="fragment">For example, the integers and strings we've been using have methods attached to them</p>
<p class="fragment">We can use the dir() function to see the methods of an object and help() to see what they do.</p>
<pre><code contenteditable class="fragment python">
a = 4
print(dir(a))
name = 'caleb'
sentence = 'the quick brown fox did the thing with the thing'
print(dir(name))
print(name.capitalize())
print(sentence.count('the'))
help(name.upper)
</code></pre>
</section>
<!-- Let's develop it: 5 minutes -->
<section>
<h3>Let's Develop It</h3>
<p>Open a Python shell and define a string varaible</p>
<p>Use 'dir(string_variable)' and the help() function to explore the various methods
<p>Hint: Like functions, some methods take arguments and others don't</p>
<p>Hint: Use help() on a method. It will tell you the arguments to use and the expected behavior</p>
<p>Hint: Don't be afraid of errors. They seem to be in a foreign language but they are there to help you. Read them carefully.</p>
</section>
<!-- Block 2 30 minutes -->
<section>
<h3>Lists</h3>
<p>A list is an ordered collection of elements</p>
<p class="fragment">In Python, a list is defined using `[ ]` with elements separated by commas, as in the following example</p>
<pre><code contenteditable class="fragment python">
words = ['list', 'of', 'strings']
</code></pre>
<p class="fragment">A list can, but doesn't have to be of all one type. A list of one type is <strong>homogenous</strong> as opposed to a list of multiple types, which is <strong>heterogeneous</strong>.</p>
<pre><code contenteditable class="fragment python">
# heterogenous list
words = [0, 'list', 'of', 3, 'strings', 'and', 'numbers']
</code></pre>
</section>
<section>
<h3>List Methods</h3>
<p>Lists have several methods, the most useful of which is `append`</p>
<p class="fragment">A list can be created as an empty list and have values added to it with `append`</p>
<pre><code contenteditable class="fragment python">
to_dos = []
to_dos.append('buy soy milk')
to_dos.append('install git')
print(to_dos)
</code></pre>
<p class="fragment">Therefore, lists are <strong>mutable</strong></p>
<p class="fragment">This means that a list can change values during the duration of a program</p>
</section>
<section>
<h3>Iteration</h3>
<p>Lists and many other collections are <strong>iterable</strong>.</p>
<p class="fragment">Once defined, we can iterate on them, performing an action with each element</p>
<pre><code contenteditable class="fragment python">
shipping_cost = 2.5
prices = [3, 4, 5.25]
costs = []
for price in prices:
costs.append(price + shipping_cost)
for cost in costs:
print(cost)
</code></pre>
</section>
<section>
<h3>Indexing</h3>
<p>An element can also be obtained from a list through <strong>indexing</strong></p>
<p class="fragment">This allows us to obtain an element without iterating through the entire collection if we just want one value.</p>
<p class="fragment">To index on a collection, follow it immediately with `[index]`. (index here is a number, variable or expression)</p>
<pre><code contenteditable class="fragment python">
numbers = [10, 20, 30]
print(numbers[0])
</code></pre>
</section>
<section>
<h3>Indexing continued</h3>
<p class="fragment">Lists and other collections in Python are <strong>zero indexed</strong>. This means that the number 0 refers to first element in the list.</p>
<pre><code contenteditable class="fragment python">
to_dos = [
'install git', 'read email', 'make lunch',
]
print(to_dos[0])
print(to_dos[1])
print(to_dos[-1])
</code></pre>
<p class="fragment">Negative numbers mean "go back from the end this many". e.g. -1 is the last element, -2 is the penultimate</p>
<p class="fragment">An IndexError results if an index exceeds the length of the list minus 1</p>
</section>
<section>
<h3>Dictionaries</h3>
<p>A <strong>dictionary</strong> (sometimes called a "hashmap") is a collection of key/value pairs, defined with '{}'</p>
<pre><code contenteditable class="fragment python">
menu_categories = {
'food': 'stuff you eat',
'beverage': 'stuff you drink',
}
</code></pre>
<p class="fragment">Think of words in a dictionary. The words are keys and the definitions are values.</p>
<p class="fragment">This dictionary would be indexed with strings such as 'food' and 'beverage' instead of integers like in a list</p>
<p class="fragment"></p>
</section>
<section>
<h3>Indexing on Dictionaries</h3>
<p>Dictionaries aren't literally just for definitions. They represent a group of mappings. A mapping might be: menu items -> costs.</p>
<p class="fragment">We can also index on dictionaries.</p>
<p class="fragment">The most common indexes are strings, but they can be whatever type the keys are.</p>
<pre><code contenteditable class="fragment python">
menu = {
'tofu': 4,
}
tofu_cost = menu['tofu']
</code></pre>
<p class="fragment">Indexing on a key that doesn't exist results in a KeyError</p>
<p class="fragment">If you aren't certain a key is present, you can use the 'get' method</p>
</section>
<section>
<h3>Dictionary Methods</h3>
<p>Some of the most essential methods are 'keys', 'values' and 'items'</p>
<pre><code contenteditable class="fragment python">
menu = {
'tofu': 4,
'pizza': 8,
'baguette': 3,
}
print(menu.keys())
print(menu.values())
print(menu.items())
print(menu.get('pizza'))
print(menu.get('water'))
print(menu.get('juice', 5))
</code></pre>
<p class="fragment">'get' will return None if the key isn't present or a default value if provided.</p>
</section>
<section>
<h3>The in operator</h3>
<p>The `in` operator is used to determine if an element is in a given collection</p>
<p class="fragment">For dictionaries, the keys are searched for the element.</p>
<pre><code contenteditable class="fragment python">
color = (255, 255, 0)
if 0 in color:
print('0 is in the color')
menu = {'tofu': 4}
print('tofu' in menu)
names = ['Mary', 'Martha', 'George']
george_present = 'George' in names
</code></pre>
</section>
<!-- Let's develop it: 15 minutes -->
<section>
<h3>Let's Develop It</h3>
<p>Write a program that opens a text file and does some processing.</p>
<ul>
<li>The program should take a word as input and determine if the word appears in the file</li>
<li>The program should use at least one function to do its work and you should be able to import this function in a Python shell and call it with a word and filename</li>
<li>Use the functions from <a href="http://nicklang.com/gdi-intro-python/examples/helpers.py">helpers.py</a> to help with reading in the lines and/or words of the file</li>
<li>Download a book in plain text from <a href="http://www.gutenberg.org/wiki/Main_Page">Project Gutenburg</a> and put it into the same directory as your python file.</li>
</ul>
<p>The next slide has some code and other resources that should help you get started</p>
</section>
<section>
<h3>Let's Develop It- Example Code</h3>
<pre><code contenteditable class="python">
from helpers import generate_cleaned_lines
def is_word_in_file(word, filename):
for line in generate_cleaned_lines(filename):
# line will be a string of each line of the file in order
# Your code goes here.
# Your code should do something with the word and line variables and assign the value to a variable for returning
input_word = raw_input("Enter a word to search for:") # input()
answer = is_word_in_file(input_word, 'pride.txt')
# Display the answer in some meaningful way
</code></pre>
<p>I have used <a href="http://nicklang.com/gdi-intro-python/examples/pride.txt">Pride and Prejudice</a> from Project Gutenburg with my example code. You can click this link and copy/paste the text into a new text file called 'pride.txt' and save it in the same folder as your code</p>
</section>
<!-- Block 3 20 minutes -->
<section>
<h3>Lists of ... Lists</h3>
<p>Lists can contain not only numbers or strings, but also other lists.</p>
<p class="fragment">Such a structure is said to be <strong>nested</strong></p>
<p class="fragment">The following is a list of lists:</p>
<pre><code contenteditable class="fragment python">
game_board = [
['O', 'X', ' '],
[' ', 'X', ' '],
[' ', ' ', ' '],
]
</code></pre>
<p class="fragment">This can be indexed successively with <code>game_board[0][1]</code></p>
</section>
<section>
<h3>Nested Lists continued</h3>
<p>A list can be appended to a list as well</p>
<pre><code contenteditable class="fragment python">
mary_to_dos = ['eat', 'work', 'pick up laundry', 'care for baby', 'sleep']
fran_to_dos = ['eat', 'work', 'call plumber', 'sleep']
baby_to_dos = ['eat', 'sleep']
all_to_dos = []
all_to_dos.append(mary_to_dos)
all_to_dos.append(fran_to_dos)
all_to_dos.append(baby_to_dos)
print(all_to_dos)
for to_dos in all_to_dos:
for to_do in to_dos:
print(to_do)
</code></pre>
<p class="fragment">What if we want to <strong>flatten</strong> the to do's?</p>
<p class="fragment">What if we want the to do's to be unique?</p>
</section>
<section>
<h3>Lists of Dictionaries</h3>
<p>One of the most common and useful nested data structures, is a list of dictionaries</p>
<pre><code contenteditable class="fragment python">
card_a = {
'suit': 'spades',
'number': 4,
}
card_b = {
'suit': 'hearts',
'number': 8,
}
hand = [card_a, card_b]
print('The hand contains:')
for card in hand:
print('A', card['number'], 'of', card['suit'])
</code></pre>
</section>
<section>
<h3>Dictionary of Lists</h3>
<p>A dictionary can also contain values that are themselves other collections, such as lists.</p>
<p class="fragment">Let's revisit the group of to do lists and find a better representation:</p>
<pre><code contenteditable class="fragment python">
mary_to_dos = ['eat', 'work', 'pick up laundry', 'care for baby', 'sleep']
fran_to_dos = ['eat', 'work', 'call plumber', 'sleep']
baby_to_dos = ['eat', 'sleep']
all_to_dos = {
'mary': mary_to_dos,
'fran': fran_to_dos,
'baby': baby_to_dos,
}
for name, to_dos in all_to_dos.items():
print(name, 'needs to: ', to_dos)
# Changing this later can be accomplished with
all_to_dos['baby'].append('cry')
</code></pre>
<p class="fragment">Now the to do lists can be indexed or modified by name</p>
</section>
<section>
<h3>Means of Combination</h3>
<p>Lists, dictionaries, and other collections are all a means of combination.</p>
<p class="fragment">They can be freely combined to create the data structure needed for a particular problem</p>
<p class="fragment">Eg. A list of dictionaries with lists</p>
<pre><code contenteditable class="fragment python">
all_tweets = [
{
'author': 'mary',
'handle': '@hadalittlelamb',
'date': '2013-01-22',
'tweets': [
'at Loco Pops enjoying a Raspberry Sage popsicle',
'Learning Python is so much fun',
],
},
]
</code></pre>
</section>
<section>
<h3>Builtins for collections</h3>
<p>Python provides several functions that help us work with these collections.</p>
<table class="fragment">
<tr>
<td>len()</td>
<td>Given a collection, return its length</td>
</tr>
<tr>
<td>range()</td>
<td>Create a list of integers in the range provided.</td>
</tr>
<tr>
<td>sorted()</td>
<td>Given a collection, returns a sorted copy of that collection</td>
</tr>
<tr>
<td>enumerate()</td>
<td>Returns a list of (index, element) from the list</td>
</tr>
<tr>
<td>zip()</td>
<td>Given one or more iterables, returns a list of tuples with an element from each iterable</td>
</tr>
</table>
</section>
<section>
<h3>Examples of using Builtins</h3>
<pre><code contenteditable class="fragment python">
# Using len() - Determines length
print(len([1, 2]))
# range() - Quickly creates a list of integers
print(range(5))
print(range(5, 10))
print(range(0, 10, 2))
print(range(9, -1, -1))
# sorted() - Sort a given list
grades = [93, 100, 60]
grades = sorted(grades)
print(grades)
</code></pre>
</section>
<section>
<h3>Builtins Examples continued</h3>
<pre><code contenteditable class="fragment python">
# enumerate() - Obtain the index of the element in the loop
print('To Do:')
to_dos = ['work', 'sleep', 'work']
for index, item in enumerate(to_dos):
print('{0}. {1}'.format(index + 1, item))
print(list(enumerate(to_dos)))
# zip()
widths = [10, 15, 20]
heights = [5, 8, 12]
for width, height in zip(widths, heights):
print('Area is {0}'.format(width * height))
</code></pre>
</section>
<!-- Let's develop it: 25 minutes -->
<section>
<h3>Let's Develop It</h3>
<p>Write a program that expands on your previous one. If it is unfinished, feel free to finish the original exercise first. To expand on it, choose one of the following:</p>
<ol>
<li>Determine how many times the user provided word appears in the file and/or what lines it appears on</li>
<li>Change the program so that it counts the number of times each word occurs. E.g. A dictionary of all words in the file, whose values are a count of their occurrences</li>
<li>Use <a href="http://nicklang.com/gdi-intro-python/examples/boilerplate.py">boilerplate.py</a> to help you improve the reusability of the program. (The comments in that file should explain the how and why)</li>
</ol>
<p>Resources for this and the previous exercise are provided on the next slide for convenience</p>
</section>
<section>
<h3>Resources</h3>
<ul>
<li>Helper functions are in <a href="http://nicklang.com/gdi-intro-python/examples/helpers.py">helpers.py</a></li>
<li>Download a book in plain text from <a href="http://www.gutenberg.org/wiki/Main_Page">Project Gutenburg</a> and put it into the same directory as your python file.</li>
<li>You can use this link for <a href="http://nicklang.com/gdi-intro-python/examples/pride.txt">Pride and Prejudice</a>. Click this link and copy/paste the text into a new text file called 'pride.txt' and save it in the same folder as your code</li>
</ul>
<pre><code contenteditable class="python">
from helpers import generate_cleaned_lines
def is_word_in_file(word, filename):
for line in generate_cleaned_lines(filename):
# line will be a string of each line of the file in order
# Your code goes here. Do something with the word and line variables
return result
input_word = raw_input("Enter a word to search for:") # input()
answer = is_word_in_file(input_word, 'pride.txt')
# Display the answer in some meaningful way
</code></pre>
</section>
<section>
<h3>Questions?</h3>
</section>
<section></section>
</div>
<footer>
<div class="copyright">
Intro to Python ~ Girl Develop It ~
<a rel="license" href="http://creativecommons.org/licenses/by-nc/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc/3.0/80x15.png" /></a>
</div>
</footer>
</div>
<script src="reveal/lib/js/head.min.js"></script>
<script src="reveal/js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/none
// Optional libraries used to extend on reveal.js
dependencies: [
{ src: 'reveal/lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'reveal/plugin/markdown/showdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'reveal/plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'reveal/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'reveal/plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'reveal/plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
</script>
</body>
</html>