PageRenderTime 24ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/set1/class4.html

https://gitlab.com/GDIBoise/gdi-intro-python
HTML | 449 lines | 371 code | 65 blank | 13 comment | 0 complexity | 8fecd97c661ab35e25ea9d194129c723 MD5 | raw file
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Intro to Python ~ Girl Develop It</title>
  6. <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.">
  7. <meta name="author" content="Girl Develop It">
  8. <meta name="apple-mobile-web-app-capable" content="yes" />
  9. <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
  10. <link rel="stylesheet" href="../reveal/css/reveal.css">
  11. <link rel="stylesheet" href="../css/gdicool.css" id="theme">
  12. <!-- For syntax highlighting -->
  13. <!-- light editor<link rel="stylesheet" href="lib/css/light.css">-->
  14. <!-- dark editor--><link rel="stylesheet" href="../css/dark.css">
  15. <!-- If use the PDF print sheet so students can print slides-->
  16. <link rel="stylesheet" href="../reveal/css/print/pdf.css" type="text/css" media="print">
  17. <!--[if lt IE 9]>
  18. <script src="lib/js/html5shiv.js"></script>
  19. <![endif]-->
  20. </head>
  21. <body>
  22. <div class="reveal">
  23. <!-- Any section element inside of this container is displayed as a slide -->
  24. <div class="slides">
  25. <!-- Opening slide -->
  26. <section>
  27. <img src = "../images/gdi_logo_badge.png">
  28. <h3>Intro to Python</h3>
  29. <h4>Class 4</h4>
  30. </section>
  31. <section>
  32. <h3>Review</h3>
  33. <ul>
  34. <li>Method calls</li>
  35. <li>Combining lists and dictionaries</li>
  36. <li>Builtins for collections</li>
  37. </ul>
  38. </section>
  39. <!-- Block 1 - Intro to Classes and OOP - 20 minutes -->
  40. <section>
  41. <h3>Functions on Dictionaries</h3>
  42. <p></p>
  43. <pre><code contenteditable class="fragment python">
  44. character = {
  45. 'x': 10,
  46. 'y': 20,
  47. 'health': 100,
  48. }
  49. def injure(character, damage):
  50. character['health'] = character['health'] - damage
  51. if character['health'] < 0:
  52. character['health'] = 0
  53. def heal(character, amount):
  54. character['health'] = character['health'] + amount
  55. if character['health'] > 100:
  56. character['health'] = 100
  57. </code></pre>
  58. </section>
  59. <section>
  60. <h3>Classes</h3>
  61. <p>A <strong>class</strong> creates a new type of object.</p>
  62. <p class="fragment">A class defines the attributes and methods of objects of that type</p>
  63. <p class="fragment">Classes are used to create new objects of that type</p>
  64. <pre><code contenteditable class="fragment python">
  65. class Character():
  66. def __init__(self, x, y, health):
  67. self.x = x
  68. self.y = y
  69. self.health = health
  70. character = Character(10, 20, 100)
  71. </code></pre>
  72. </section>
  73. <section>
  74. <h3>A Sense of Self</h3>
  75. <p>The first argument to every method is <strong>self</strong>.</p>
  76. <p class="fragment">self contains the attributes and methods for the current object</p>
  77. <pre><code contenteditable class="fragment python">
  78. class Character():
  79. def __init__(self, x, y, health):
  80. self.x = x
  81. self.y = y
  82. self.health = health
  83. character = Character(10, 20, 100)
  84. </code></pre>
  85. </section>
  86. <section>
  87. <h3>The __init__ Method</h3>
  88. <p>This method defines what the class should do when creating a new object.</p>
  89. <pre><code contenteditable class="fragment python">
  90. class Character():
  91. def __init__(self, x, y, health):
  92. self.x = x
  93. self.y = y
  94. self.health = health
  95. character_a = Character(10, 20, 100)
  96. character_b = Character(10, 20, 100)
  97. </code></pre>
  98. <p class="fragment">To create a new Character, the syntax looks like a function call. These arguments are passed to the __init__ method</p>
  99. </section>
  100. <section>
  101. <h3>Class Methods</h3>
  102. <p>A class also defines <strong>methods</strong>, which are functions that operate on objects of that type</p>
  103. <p class="fragment">Assigning values to an attribute on self is how we <strong>mutate</strong> the object's state.</p>
  104. <pre><code contenteditable class="fragment python">
  105. # inside the character class
  106. def heal(self, amount):
  107. self.health = self.health + amount
  108. if self.health > 100:
  109. self.health = 100
  110. def injure(self, amount):
  111. self.health = self.health - amount
  112. if self.health < 0:
  113. self.health = 0
  114. character = Character(10, 20, 100)
  115. character.injure(10)
  116. </code></pre>
  117. </section>
  118. <!-- Let's develop it: 10 minutes -->
  119. <section>
  120. <h3>Let's Develop It</h3>
  121. <ul>
  122. <li>In your text editor, create your own class with an __init__ method, and at least one other method.</li>
  123. <li>Open a Python shell and import the class. Create one or more objects from the class</li>
  124. <li>If time allows, create a function that creates objects from your class, calls a method, and prints one of its attributes</li>
  125. <li>Use the next slide as an example</li>
  126. </ul>
  127. </section>
  128. <section>
  129. <pre><code contenteditable class="python">
  130. # in character.py
  131. class Character():
  132. def __init__(self, x, y, health):
  133. self.x = x
  134. self.y = y
  135. self.health = health
  136. def heal(self, amount):
  137. self.health = self.health + amount
  138. if self.health > 100:
  139. self.health = 100
  140. </code></pre>
  141. <pre><code contenteditable class="python">
  142. # in Python shell
  143. from character import Character
  144. character_a = Character(10, 20, 100)
  145. character_a.injure(10)
  146. print "character health is: " + character_a.health
  147. </code></pre>
  148. </section>
  149. <!-- Block 2 - Inheritance and Composition 20 Minutes -->
  150. <section>
  151. <h3>Inheritance</h3>
  152. <p>A class can <strong>inherit</strong> from another class.</p>
  153. <p class="fragment">A class that inherits from another is called the "child class" and obtains the methods and attributes of its "parent"</p>
  154. <pre><code contenteditable class="fragment python">
  155. class Mobile(object):
  156. """
  157. An object with an x, y position, and methods for moving
  158. """
  159. def __init__(self, x, y):
  160. self.x = x
  161. self.y = y
  162. def move_up():
  163. self.y = self.y - 1
  164. # ... methods for move_down, move_left, and move_right
  165. </code></pre>
  166. </section>
  167. <section>
  168. <h3>Inheritance Continued</h3>
  169. <p>The move_up method is <strong>overridden</strong> in the child class below:</p>
  170. <pre><code contenteditable class="fragment python">
  171. class BoundedMobile(Mobile):
  172. """
  173. An object with an x, y position, and methods for moving
  174. The x, y position must be within bounds
  175. """
  176. def move_up():
  177. self.y = self.y - 1
  178. if self.y < 0:
  179. self.y = 0
  180. </code></pre>
  181. <p class="fragment">See <a href="http://calebsmith.github.io/gdi-intro-python/examples/mobile.py">mobile.py</a> for a more complete example.</p>
  182. </section>
  183. <section>
  184. <h3>What's Super about Super</h3>
  185. <p><strong>super</strong> is often helpful when writing methods that override the method of the parent class</p>
  186. <pre><code contenteditable class="fragment python">
  187. class BoundedMobile(Mobile):
  188. """
  189. An object with an x, y position, and methods for moving
  190. The x, y position must be within bounds
  191. """
  192. def move_up():
  193. super(BoundedMobile, self).move_up()
  194. if self.y < 0:
  195. self.y = 0
  196. </code></pre>
  197. <p class="fragment">The call to super() takes the name of the child class, followed by self. This is followed by the method call and any arguments to pass to it</p>
  198. </section>
  199. <section>
  200. <h3>Composition</h3>
  201. <p>Classes can also use the technique of <strong>composition</strong></p>
  202. <p class="fragment">This simply means that a given object contains other objects within it.</p>
  203. <p class="fragment">This often leads to a clearer and simpler design</p>
  204. <pre><code contenteditable class="fragment python">
  205. class Grid(object):
  206. def __init__(self, x_limit, y_limit):
  207. self.x_limit = x_limit
  208. self.y_limit = y_limit
  209. self.mobiles = []
  210. def add_mobile(self, x, y):
  211. mob = BoundedMobile(x, y, self.x_limit, self.y_limit)
  212. mobs = self.mobiles.get((x, y), [])
  213. mobs.append(mob)
  214. self.mobiles[(x, y)] = mobs
  215. </code></pre>
  216. </section>
  217. <section>
  218. <h3>Composition Continued</h3>
  219. <p>Given the class on the previous slide, the following code creates mobiles within the grid object. (Complete code is available in the aforementioned <a href="http://calebsmith.github.io/gdi-intro-python/examples/mobile.py">mobile.py</a> file.)</p>
  220. <pre><code contenteditable class="fragment python">
  221. from mobile import Grid
  222. grid = Grid(7, 7)
  223. grid.add_mobile(1, 2)
  224. grid.add_mobile(0, 1)
  225. grid.add_mobile(0, 1)
  226. grid.display_grid()
  227. </code></pre>
  228. </section>
  229. <!-- Let's develop it: 10 minutes -->
  230. <section>
  231. <h3>Let's Develop It</h3>
  232. <p>Create a class that uses inheritance, composition, or both.</p>
  233. <p>To help you, use your work from the last exercise or the classes from <a href="http://calebsmith.github.io/gdi-intro-python/examples/mobile.py">mobile.py</a></p>
  234. </section>
  235. <!-- Block 3 - Functional Programming - 20 Minutes -->
  236. <section>
  237. <h3>List Comprehensions</h3>
  238. <p>I have a list and I have something I want to do to each element to create a new list</p>
  239. <pre><code contenteditable class="fragment python">
  240. squares = []
  241. for number in range(11):
  242. squares.append(number ** 2)
  243. </code></pre>
  244. <p class="fragment">This pattern is so common, there is a shorter way to express it:</p>
  245. <pre><code contenteditable class="fragment python">
  246. squares = [number ** 2 for number in range(11)]
  247. </code></pre>
  248. <p class="fragment">This is called a <strong>list comprehension</strong></p>
  249. </section>
  250. <section>
  251. <h3>Generators</h3>
  252. <p>A <strong>generator</strong> is like a list, but it is evaluated when it is used rather than when it is defined.</p>
  253. <p class="fragment">Generators are useful when the list may be very large or when the task is time consuming</p>
  254. <pre><code contenteditable class="fragment python">
  255. #Define a generator
  256. def find_squares(numbers):
  257. for number in numbers
  258. yield number ** 2
  259. #Iterate on a generator like a list
  260. for square in find_squares(range(10)):
  261. print square
  262. </code></pre>
  263. <p class="fragment">A function with a <strong>yield</strong> statement creates a generator. Each yield statement "yields" the next value in the sequence</p>
  264. </section>
  265. <section>
  266. <h3>Generator Comprehensions</h3>
  267. <p>A <strong>generator comprehension</strong> is created the same way as list comprehension, but replacing the square brackets with parenthesis.</p>
  268. <pre><code contenteditable class="fragment python">
  269. ten_squares = (number ** 2 for number in range(10))
  270. </code></pre>
  271. <p class="fragment">These are used liberally in the functions of <a href="http://calebsmith.github.io/gdi-intro-python/examples/books.py">books.py</a> example from class 3.</p>
  272. </section>
  273. <section>
  274. <h3>Higher order functions</h3>
  275. <p>A <strong>higher order function</strong> is a function that returns a function, takes a function as an argument, or both</p>
  276. <p class="fragment">One commonly used higher order function that is a Python builtin is called <strong>map</strong></p>
  277. <pre><code contenteditable class="fragment python">
  278. # Define any function
  279. def sqaure(number):
  280. return number ** 2
  281. # Pass the function to map along with an iterable
  282. squares = map(square, range(10))
  283. </code></pre>
  284. <p class="fragment">N.B. - map has performance problems for large data sets and should only be used when the data set is well defined and somewhat small.</section>
  285. </section>
  286. <section>
  287. <h3>Let's Develop It</h3>
  288. <p>Choose among any of these projects (Resources available on the next page):</p>
  289. <ul>
  290. <li>Search the Web - Write a program that searches the web using DuckDuckGo and displays results.
  291. </li>
  292. <li>Encryption - Write a program that encrypts a string from user input, or file and is able to decrypt it as well.
  293. </li>
  294. <li>Command Line Game - Create a simple game that runs inside the terminal.
  295. </li>
  296. </section>
  297. <section>
  298. <h3>Let's Develop It Resources</h3>
  299. <table>
  300. <tr>
  301. <td>Search the Web</td>
  302. <td><a href="https://github.com/crazedpsyc/python-duckduckgo/">python-duckduckgo</a> library to get started. Download duckduckgo.py and put it in the same directory as your code. Use the query() function it provides to begin. (HINT: Results are often empty, but 'related' list usually has a few hits.)</td>
  303. </tr>
  304. <tr>
  305. <td>Encryption</td>
  306. <td>Read about the <a href="https://en.wikipedia.org/wiki/Caesar_cipher">Caesar Cipher</a> or find a similarly simple encryption mechanism online. You should find the ord() and chr() functions helpful, as well as the modulus operator '%'</td>
  307. </tr>
  308. </table>
  309. <p>continued on next page...</p>
  310. </section>
  311. <section>
  312. <h3>Let's Develop It Resources Continued</h3>
  313. <table>
  314. <tr>
  315. <td>Command Line Game</td>
  316. <td>This might be a text adventure with paragraphs of text followed by a series of choices for the user. A choice maps to another node in the story (another paragraph with choices). You might try storing the paragraphs separately in a text file. The format might be something different, such as a series of "rooms", each with a description, for the user to explore by entering commands such as "go west". Examples of these kinds of games are <a href="https://en.wikipedia.org/wiki/Colossal_Cave_Adventure">Colossal Cave Adventure</a> and <a href="https://en.wikipedia.org/wiki/Zor">Zork</a></td>
  317. </tr>
  318. </table>
  319. </section>
  320. <section>
  321. <h3>Future Resources</h3>
  322. <p></p>
  323. <table>
  324. <tr>
  325. <td><a href="http://docs.python.org/2/">Python.org Documentation</a></td>
  326. <td>Official Python Documentation</td>
  327. </tr>
  328. <tr>
  329. <td><a href="http://www.greenteapress.com/thinkpython/html/index.html">Think Python</a></td>
  330. <td>Online and print book with exercises.</td>
  331. </tr>
  332. <tr>
  333. <td><a href="http://learnpythonthehardway.org/book/">Learn Python the Hard Way</a></td>
  334. <td>Online and print book with exercises</td>
  335. </tr>
  336. <tr>
  337. <td><a href="https://developers.google.com/edu/python/">Google's Python Class</a></td>
  338. <td>Video lectures coupled with exercises</td>
  339. </tr>
  340. <tr>
  341. <td><a href="http://newcoder.io/tutorials/">New Coder</a></td>
  342. <td>Ideas for slightly larger projects and resources to get you started. Projects include accessing API's, scraping pages, writing IRC bots, and others.</td>
  343. </tr>
  344. <tr>
  345. <td><a href="http://girldevelopit.com/">Girl Develop It</a></td>
  346. <td>Local workshops, events, and coding sessions</td>
  347. </tr>
  348. </table>
  349. </section>
  350. <section>
  351. <h3>Questions?</h3>
  352. </section>
  353. </div>
  354. <footer>
  355. <div class="copyright">
  356. Intro to Python ~ Girl Develop It ~
  357. <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>
  358. </div>
  359. </footer>
  360. </div>
  361. <script src="../reveal/lib/js/head.min.js"></script>
  362. <script src="../reveal/js/reveal.min.js"></script>
  363. <script>
  364. // Full list of configuration options available here:
  365. // https://github.com/hakimel/reveal.js#configuration
  366. Reveal.initialize({
  367. controls: true,
  368. progress: true,
  369. history: true,
  370. theme: Reveal.getQueryHash().theme, // available themes are in /css/themes
  371. transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/none
  372. // Optional libraries used to extend on reveal.js
  373. dependencies: [
  374. { src: '../reveal/lib/js/classList.js', condition: function() { return !document.body.classList; } },
  375. { src: '../reveal/plugin/markdown/showdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
  376. { src: '../reveal/plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
  377. { src: '../reveal/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
  378. { src: '../reveal/plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
  379. { src: '../reveal/plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
  380. ]
  381. });
  382. </script>
  383. </body>
  384. </html>