├── .gitignore ├── .gitmodules ├── AUTHORS ├── README.md ├── about.html ├── citycamp ├── index.html └── slides │ ├── contents.md │ ├── exercises.md │ ├── menu.md │ ├── part1.md │ ├── part2.md │ └── part3.md ├── css ├── dark.css ├── fonts │ └── Gotham │ │ ├── Gotham-Bold.otf │ │ └── Gotham-Book.otf └── gdicool.css ├── examples ├── board.dat ├── boilerplate.py ├── books.py ├── durham_establishments.csv ├── english.txt ├── game1.py ├── game2.py ├── game3.py ├── game4.py ├── game5.py ├── game6.py ├── game7.py ├── geometry.py ├── helpers.py ├── knights.py ├── mobile.py └── pride.txt ├── images ├── cc-license.png ├── gdi_logo_badge.png └── pink-logo.png ├── index.html ├── requirements.txt ├── server.py ├── set1 ├── class1.html ├── class2.html ├── class3.html ├── class4.html └── index.html └── set2 ├── index.html └── slides ├── contents.md ├── exercises.md ├── menu.md ├── part1.md ├── part2.md ├── part3.md └── part4.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *~ 3 | *.swp 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "reveal"] 2 | path = reveal 3 | url = https://github.com/hakimel/reveal.js 4 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Contributors of content and ideas 2 | 3 | * @calebsmith 4 | * @rebecca-caktus 5 | * @fxdgear 6 | * @lesliehealray 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Intro to Python 2 | 3 | The slides for this course can be viewed [here](http://calebsmith.github.io/gdi-intro-python/#/) 4 | 5 | This is the Girl Develop It RDU Intro to Python course. Material is loosely based on Think Python by Allen B. Downey and written by Caleb Smith 6 | 7 | The course is divided into 4 sections. Each of the slides and practice files can be customized according to the needs of a given class or audience. 8 | 9 | 10 | Development Setup 11 | ----------------- 12 | 13 | Make sure you have git installed on your computer, and open a terminal window. 14 | 15 | You'll need to clone this repository to your computer: 16 | 17 | git clone https://github.com/calebsmith/gdi-intro-python.git 18 | 19 | reveal.js is stored as a git submodule. To set up the reveal.js code: 20 | 21 | cd gdi-intro-python 22 | git submodule init 23 | git submodule update 24 | 25 | (Note: Some internet connections (including our class location) block SSH 26 | connections on Port 22. If you get an error running the above, edit 27 | ``gdi-into-python/.git/modules/reveal/config`` and change the line 28 | ``url = git://git@github.com/girldevelopit/reveal.js.git`` to 29 | ``url = https://github.com/girldevelopit/reveal.js.git`` and run the above 30 | commands again.) 31 | 32 | To get the code running, run ``python server.py`` from the gdi-intro-python 33 | directory. 34 | 35 | Finally, navigate to ``http://localhost:8000/`` in your browser. 36 | 37 | Livereload 38 | ---------- 39 | 40 | This is an optional part of running the slides locally. This is only needed if 41 | you would like for the browser to reload the slides on save 42 | 43 | * For a livereload server, `pip install -r requirements`. (If you don't have a 44 | full Python environment, there are various other livereload server 45 | implementations such as those in Ruby or Node.js) 46 | * Install the livereload chrome extension. 47 | * Run the server.py server in a terminal using `python server.py` and open a 48 | chrome to ``http://localhost:8000/`` 49 | -------------------------------------------------------------------------------- /about.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Intro to Python ~ Girl Develop It 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 |
33 | 34 |
35 | 36 |
37 |

About

38 |

39 | This project tracks the slides used for teaching the Intro 40 | to Python class with Girl Develop It RDU. The "revisions" 41 | listed at the home page represent the state of slides as 42 | they appeared during a given set of classes. Each of these 43 | revisions is broken into "classes" or "parts" for seperate 44 | class sessions or segments of those class sessions. 45 |

46 |

47 | In general, the most recent set of slides is preferred for 48 | anyone seeking to bootstrap their own course with this 49 | material or self study. Old revisions are primarily kept 50 | available for former students as a reference. 51 |

52 |
53 |
54 |
55 | 59 |
60 |
61 | 62 | 63 | 64 | 65 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /citycamp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Intro to Python ~ Girl Develop It 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 |
28 | 29 |
33 |
34 |
35 |
36 | 40 |
41 |
42 | 43 | 44 | 45 | 46 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /citycamp/slides/contents.md: -------------------------------------------------------------------------------- 1 | ####[Part 1](?part=part1) - Intro to programming in Python 2 | 3 | What is programming? What is Python? We'll tackle these concepts, set up a development environment, and get started working in the Python shell. 4 | @@@ 5 | 6 | ####[Part 2](?part=part2) - Structured programming: Functions, Loops, and conditionals 7 | 8 | We'll be creating small programs in the text editor, implementing control flow and loading these programs into the shell. 9 | @@@ 10 | 11 | ####[Part 3](?part=part3) - Python data structures and other essential built-ins 12 | 13 | Lists, dictionaries and other built-in containers give the Python programmer tremendous power. We'll use these combined with other Python built-ins to process text files for information. 14 | @@@ 15 | 16 | ####[Exercises](?part=exercises) - Additional Exercises 17 | -------------------------------------------------------------------------------- /citycamp/slides/exercises.md: -------------------------------------------------------------------------------- 1 | ![Girl Develop It Logo](../images/gdi_logo_badge.png) 2 | 3 | ###Intro to Python 4 | ####Additional Exercises 5 | @@@ 6 | 7 | ###Functions 8 | 9 | * Write a program that uses at least one function to solve a geometry problem 10 | 11 | * The program will generally have three steps: 12 | 13 | * Obtain input 14 | * Call a function to calculate the answer 15 | * Display the answer 16 | 17 | * Hint: You can take user input with raw_input() as before, or use the example 18 | below to take arguments from the command line 19 | * Download [geometry.py](http://calebsmith.github.io/gdi-intro-python/examples/geometry.py) and use it as an example 20 | 21 | Note: Let's Develop It 15 Minutes 22 | 23 | @@@ 24 | 25 | ###Text processing 26 | 27 | Write a program that opens a text file and does some processing. 28 | 29 | * The program should take a word as input and determine if the word appears in the file 30 | 31 | * 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 32 | 33 | The next page lists the things you will need. 34 | 35 | Note: Let's develop it: 15 minutes 36 | 37 | @@@ 38 | 39 | ###Text processing - Requirements 40 | 41 | * Use the functions from [helpers.py](http://calebsmith.github.io/gdi-intro-python/examples/helpers.py) to help with reading in the lines and/or words of the file 42 | 43 | * Download a plain text english dictionary like the following: [english.txt](http://calebsmith.github.io/gdi-intro-python/examples/english.txt) and put it into the same directory as your python file. 44 | 45 | * Download a book in plain text from [Project Gutenburg](http://www.gutenberg.org/wiki/Main_Page) and put it into the same directory as your python file. 46 | 47 | The next slide shows some code to help you get started. 48 | 49 | @@@ 50 | 51 | ###Text processing - Example Code 52 | 53 | ```python 54 | from helpers import generate_cleaned_lines 55 | 56 | def is_word_in_file(word, filename): 57 | for line in generate_cleaned_lines(filename): 58 | # line will be a string of each line of the file in order 59 | # Your code goes here. 60 | # Your code should do something with the word and line variables and assign the value to a variable for returning 61 | input_word = raw_input("Enter a word to search for:") 62 | answer = is_word_in_file(input_word, 'pride.txt') 63 | # Display the answer in some meaningful way 64 | ``` 65 | 66 | I have used [Pride and Prejudice](http://calebsmith.github.io/gdi-intro-python/examples/pride.txt) 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 67 | -------------------------------------------------------------------------------- /citycamp/slides/menu.md: -------------------------------------------------------------------------------- 1 | Girl Develop It Logo 2 | 3 | ###Intro to Python 4 | ####Menu 5 | 6 | [Section 1](?part=part1) 7 | [Section 2](?part=part2) 8 | [Section 3](?part=part3) 9 |
10 | [Additional Exercises](?part=exercises) 11 | [Contents](?part=contents) 12 | -------------------------------------------------------------------------------- /citycamp/slides/part1.md: -------------------------------------------------------------------------------- 1 | ![Girl Develop It Logo](../images/gdi_logo_badge.png) 2 | 3 | ###Intro to Python 4 | ####Section 1 5 | @@@ 6 | 7 | ## Welcome 8 | Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction. 9 | 10 | Some rules 11 | 12 | * We are here for you 13 | * Every question is important 14 | * Help each other 15 | * Have fun 16 | @@@ 17 | 18 | ###This Session 19 | 20 | * Why Python? 21 | * What is programming? 22 | * Variables and arithmetic 23 | * Statements and Error Messages 24 | @@@ 25 | 26 | ###Why Python? 27 | 28 | * Suitable for beginners, yet used by professionals 29 | * Readable, maintainable code 30 | * Rapid rate of development 31 | * Few "magical" side-effects 32 | * Variety of applications 33 | Note: Block 1 begins - 25 minutes 34 | @@@ 35 | 36 | ###What is Python used for? 37 | 38 | * System Administration (Fabric, Salt, Ansible) 39 | * 3D animation and image editing (Maya, Blender, Gimp) 40 | * Scientific computing (numpy, scipy) 41 | * Web development (Django, Flask) 42 | * Game Development (Civilization 4, EVE Online) 43 | @@@ 44 | 45 | ###Who is using Python? 46 | 47 | * Disney 48 | * Dropbox 49 | * Canonical and Red Hat 50 | * Google 51 | * NASA 52 | * Caktus 53 | @@@ 54 | 55 | ###What is programming? 56 | 57 | * Teaching the computer to do a task 58 | * A program is made of one or more files of code 59 | * Programming code is human readable but also needs a form that the computer can run 60 | * Don't focus on what's "under the hood" for now. We will "drive the car" first 61 | @@@ 62 | 63 | ##Block 2 64 | Note: 30 minutes 65 | @@@ 66 | 67 | ###Working in repl.it 68 | 69 | Navigate to http://repl.it in a browser. Find "Python3" under languages 70 | 71 | * Follow along with the examples in the slides. Type them in! 72 | * Feel free to explore as well. You will not accidentally break things 73 | 74 | @@@ 75 | 76 | ###Variables and Arithmetic 77 | ```python 78 | > 3 + 4 79 | => 7 80 | > 2 * 4 81 | => 8 82 | > 6 - 2 83 | => 4 84 | > 4 / 2 85 | => 2 86 | ``` 87 | 88 | ```python 89 | > a = 2 90 | > b = 3 91 | > c = a + b 92 | > print(c) 93 | => 5 94 | ``` 95 | ```python 96 | > a = 0 97 | > a = a + .5 98 | > print(a) 99 | => 0.5 100 | ``` 101 | @@@ 102 | 103 | ###Strings 104 | ```python 105 | > a = 'Hello ' 106 | > b = 'World' 107 | > c = a + b 108 | > print(c) 109 | => 'Hello World' 110 | ``` 111 | @@@ 112 | 113 | ###Data types 114 | * Variables are a name for some data 115 | * Variables always have a "type" 116 | * The type defines what it can do 117 | * The type can be found using: type() 118 | 119 | ```python 120 | > print type(4) 121 | => 122 | > a = 4 123 | > print type(a) 124 | => 125 | > print type("But I don't like spam") 126 | => 127 | > print type(3.5) 128 | => 129 | ``` 130 | @@@ 131 | 132 | ###Type Errors 133 | * Variables of a given type can be used with a set of operators 134 | * An int or float can be used with any of: +, -, \*, / 135 | * A string can be used with any of: +, \* 136 | * What happens if we try to use division or subtraction with a string? 137 | ```python 138 | > print "Spam" / "eggs" 139 | Traceback (most recent call last): 140 | File "", line 1, in 141 | TypeError: unsupported operand type(s) for /: 'str' and 'str' 142 | ``` 143 | @@@ 144 | 145 | ###Errors 146 | * An Exception gives us some information about the cause of the error 147 | * Some examples are SyntaxError, TypeError and NameError exceptions. 148 | @@@ 149 | 150 | ###Errors - continued ... 151 | 152 | * A \# is a code comment. These are not evaluated by Python 153 | 154 | ```python 155 | # SyntaxError - Doesn't conform to the rules of Python. 156 | # This statement isn't meaningful to the computer 157 | > 4spam)eggs(garbage) + 10 158 | 159 | # NameError - Using a name that hasn't been defined yet. 160 | > a = 5 161 | > print b 162 | 163 | # TypeError - Using an object in a way that its type does not support 164 | > 'string1' / 'string2' 165 | ``` 166 | @@@ 167 | 168 | ###Let's Develop It 169 | * We'll practice what we've learned in the shell 170 | * Review the slides on your computer and practice entering anything you didn't fully understand before 171 | * Ask the teacher or a TA for any help 172 | Note: Let's develop it: 5 minutes. 173 | @@@ 174 | 175 | ###User Input 176 | To obtain user input, use 'input()'. This will become a string 177 | 178 | We use float() to make it a number 179 | 180 | ```python 181 | input_value = input("Enter a radius:") 182 | radius = float(input_value) 183 | area = 3.14159 * radius * radius 184 | print('The area of a circle with radius', input_value, 'is', area) 185 | ``` 186 | @@@ 187 | 188 | ###Let's Develop It 189 | Write your own program that uses input and does something else with the value 190 | 191 | You can use float() to treat the input as a number if you need a number, or you can use the input directly if you need a string 192 | 193 | Note: Let's develop it: 10 minutes 194 | @@@ 195 | 196 | ###Any Questions? 197 | -------------------------------------------------------------------------------- /citycamp/slides/part2.md: -------------------------------------------------------------------------------- 1 | ![Girl Develop It Logo](../images/gdi_logo_badge.png) 2 | 3 | ###Intro to Python 4 | ####Section 2 5 | @@@ 6 | 7 | ###This Session 8 | * Boolean Expressions and Conditionals 9 | * Lists and Loops 10 | @@@ 11 | 12 | ###Boolean Expressions 13 | Compare values and return True or False. These are *Boolean expressions* 14 | 15 | * Test for equality by using == 16 | 17 | ```python 18 | > a = 5 19 | > b = 5 20 | > print(a == b) 21 | => True 22 | > # Combine comparison and assignment 23 | > c = a == b 24 | > print(c) 25 | => True 26 | ``` 27 | 28 | Note: Block 1 - 25 Minutes 29 | @@@ 30 | 31 | ###Comparison Operators 32 | 33 | The following chart shows the various Boolean operators 34 | 35 | Expression | Tests 36 | -----------|----------------- 37 | a == b | a is equal to b 38 | a != b | a does not equal b 39 | a < b | a is less than b 40 | a > b | a is greater than b 41 | a <= b | a is less than or equal to b 42 | a >= b | a is greater than or equal to b 43 | @@@ 44 | 45 | ### Comparison Examples 46 | 47 | ```python 48 | > a = 3 49 | > b = 4 50 | > print(a != b) 51 | => True 52 | > print(a <= 3) 53 | => True 54 | > print(a >= 4) 55 | => False 56 | ``` 57 | @@@ 58 | 59 | ###Conditionals 60 | 61 | * Conditional - different coderuns depending on comparison 62 | * We achieve this using **if** statements 63 | 64 | ```python 65 | if x == 5: 66 | print('x is equal to 5') 67 | ``` 68 | @@@ 69 | 70 | ###Else 71 | 72 | Often useful to run a different block if the statement is false. Use **else** 73 | 74 | ```python 75 | if x == 5: 76 | print('x is equal to 5') 77 | else: 78 | print('x is not equal to 5') 79 | ``` 80 | @@@ 81 | 82 | ###Indentation 83 | 84 | The line that begins a new block ends with a colon. 85 | 86 | **blocks** begin when text is indented and end when unindented 87 | 88 | Let's look at the previous example again with a few minor changes and examine the meaning of its indentation 89 | 90 | ```python 91 | if x == 5: 92 | print('x is equal to 5' 93 | a = 1 94 | print('Still in the x == 5 block') 95 | else: 96 | print('x is not equal to 5') 97 | a = 2 98 | print('Outside of if and else blocks. This will run regardless' 99 | print('Value of a is', a) 100 | ``` 101 | @@@ 102 | 103 | ###Chained conditionals 104 | Conditionals can be **chained** 105 | 106 | ```python 107 | if x > 5: 108 | print('x is greater than 5') 109 | elif x < 5: 110 | print('x is less than 5') 111 | else: 112 | print('x is equal to 5') 113 | ``` 114 | @@@ 115 | 116 | ###Nested conditionals 117 | Conditionals can also be **nested** 118 | 119 | ```python 120 | if x > 5: 121 | print('x is greater than 5') 122 | if x > 10: 123 | print('...it is also greater than 10') 124 | print('Done evaluating the x > 10 block') 125 | print('Done evaluating the x > 5 block') 126 | ``` 127 | @@@ 128 | 129 | ###Let's Develop It 130 | Write a program that uses if statements to determine what to do given some user input 131 | 132 | Example: 133 | ```python 134 | health = 100 135 | print("A vicious warg is chasing you.") 136 | print("Options:") 137 | print("1 - Hide in the cave.") 138 | print("2 - Climb a tree.") 139 | input_value = input("Enter choice:") 140 | if input_value == '1': 141 | print('You hide in a cave.') 142 | print('The warg finds you and injures your leg with its claws') 143 | health = health - 10 144 | elif input_value == '2': 145 | print('You climb a tree.') 146 | print('The warg eventually looses interest and wanders off') 147 | print("Game under construction. Come back later") 148 | ``` 149 | Note: Let's develop it: 15 minutes 150 | @@@ 151 | 152 | ###Iteration 153 | The repeated execution of a set of statements is called **iteration** 154 | 155 | One way to acheive this, is with the **while** loop. 156 | ```python 157 | x = 10 158 | while x > 0: 159 | print(x) 160 | x = x - 1 161 | print('Done') 162 | ``` 163 | 164 | The while statement takes a boolean expression. 165 | While it is True, the block is repeated 166 | 167 | Note: Block 2 - 25 minutes 168 | @@@ 169 | 170 | ###break 171 | 172 | A loop can terminate at any point with a **break** 173 | 174 | ```python 175 | while True: 176 | name = raw_input("What is your name (type 'quit' to quit)? ") 177 | if name == 'quit': 178 | break 179 | print("Hello,", name) 180 | ``` 181 | @@@ 182 | 183 | ###While loops example 184 | Consider the following example that uses iteration to derive a factorial 185 | 186 | ```python 187 | input_value = raw_input('Enter a positive integer:') 188 | n = int(input_value) 189 | result = 1 190 | while n > 1: 191 | result = result * n 192 | n = n - 1 193 | print("The factorial of " + input_value + " is: ", result) 194 | ``` 195 | @@@ 196 | 197 | ###For loops 198 | 199 | * Looping through a collection can be accomplished with a **for** loop 200 | 201 | First we need a collection. We create a **list** of numbers to loop over. 202 | 203 | ```python 204 | numbers = [1, 3, 8] 205 | for number in numbers: 206 | print("The current number is: ", number) 207 | ``` 208 | @@@ 209 | 210 | ###For loops in detail 211 | 212 | ```python 213 | numbers = [1, 3, 8] 214 | for number in numbers: 215 | print("The current number is:", number) 216 | ``` 217 | 218 | The for loop has three parts: 219 | 220 | * The collection to loop over - numbers 221 | * The name to give each element - number 222 | * The block of statements to execute with the element - The two print statements 223 | @@@ 224 | 225 | ###An Example 226 | 227 | ``` 228 | numbers = [1, 3, 8] 229 | print(len(numbers)) 230 | ``` 231 | 232 | ``` 233 | numbers = [1, 3, 8] 234 | counter = 0 235 | for number in numbers: 236 | counter = counter + 1 237 | print(counter) 238 | ``` 239 | 240 | @@@ 241 | 242 | ###Let's Develop It 243 | * Write a program that takes numbers from user input and adds thems all 244 | together for a final result. 245 | * This program should stop taking input, display the answer and exit when the user types "quit". 246 | * Hint: 247 | ```python 248 | result = 0 249 | while True: 250 | input_value = raw_input("Enter a number:") 251 | if input_value == 'quit': 252 | # insert code to leave the loop here 253 | ... (put more code here) ... 254 | print("The final sum is", result) 255 | ``` 256 | 257 | Note: Let's Develop It - 15 minutes 258 | @@@ 259 | 260 | 261 | ###Functions 262 | 263 | - A named unit of code that performs a specific task 264 | 265 | - To use a function, call it with () 266 | 267 | We have already called print, input, type, int, float, and len 268 | 269 | ```python 270 | > print(type(3)) 271 | => 272 | > numbers = [1, 2, 3] 273 | > print(len(numbers)) 274 | => 3 275 | ``` 276 | 277 | Note: Block 3 - 30 Minutes 278 | @@@ 279 | 280 | ###Function calls 281 | 282 | ```python 283 | # Repeating the previous example for reference 284 | > a = 3 285 | > print(type(a)) 286 | => 287 | ``` 288 | 289 | A function can take **arguments** 290 | 291 | In the example above, the variable `a` is passed as an argument to the function `type` 292 | 293 | A function call can be an argument to another function call. 294 | 295 | ```python 296 | # Some more function call examples 297 | > str(int(3.2)) 298 | => '3' 299 | ``` 300 | @@@ 301 | 302 | ###Function definition 303 | 304 | The following example is a **function definition**. This allows us to create our own functions 305 | 306 | ```python 307 | def print_greeting(name): 308 | print("Hi", name) 309 | print("How are you") 310 | ``` 311 | 312 | The function definition has the following parts 313 | 314 | * The def keyword signifies we are defining a function 315 | * The name of the function being defined - `print_greeting` 316 | * The parameters in parentheses - `name` 317 | * The function body 318 | @@@ 319 | 320 | ###Function returns 321 | 322 | A function can also **return** a value 323 | 324 | ``` 325 | def plus_5(x): 326 | return x + 5 327 | 328 | y = plus_5(4) 329 | ``` 330 | 331 | * Allows for calling a function for a value (rather than printing) 332 | * No return? -> Returns the value *None* 333 | 334 | Notes: substitution method 335 | @@@ 336 | 337 | ###Functions with no arguments 338 | 339 | A function does not have to take arguments, as in the following example: 340 | 341 | ```python 342 | def newline(): 343 | print('') 344 | 345 | newline() 346 | # prints an empty line. None is returned 347 | ``` 348 | 349 | This is useful when the function is intended to always do the same thing 350 | @@@ 351 | 352 | ###Scope 353 | 354 | The **scope** of a variable is the area of code where it is valid 355 | 356 | Variables defined within a function can not be used elsewhere. 357 | 358 | ```python 359 | def get_average(a, b): 360 | total = a + b 361 | return total / 2.0 362 | 363 | avg = get_average(10, 20) 364 | ``` 365 | 366 | Note: Draw a diagram with bubbles 367 | @@@ 368 | 369 | ###Let's Develop It 370 | 371 | * Create some functions that draw shapes with a turtle 372 | 373 | [http://www.skulpt.org/](http://www.skulpt.org/) 374 | 375 | ``` 376 | # Put this at the top 377 | import turtle 378 | 379 | tina = turtle.Turtle() 380 | 381 | forward = lambda n: tina.forward(n) 382 | left = lambda n: tina.left(n) 383 | right = lambda n: tina.right(n) 384 | ``` 385 | 386 | @@@ 387 | 388 | ###Example 389 | 390 | ``` 391 | def draw_square(): 392 | forward(30) 393 | right(90) 394 | forward(30) 395 | right(90) 396 | forward(30) 397 | right(90) 398 | forward(30) 399 | right(90) 400 | 401 | draw_square() 402 | ``` 403 | @@@ 404 | 405 | ###Questions? 406 | -------------------------------------------------------------------------------- /css/dark.css: -------------------------------------------------------------------------------- 1 | /* Tomorrow Night Theme */ 2 | /* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ 3 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 4 | /* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ 5 | .tomorrow-comment, pre .comment, pre .title { 6 | color: #969896; 7 | } 8 | 9 | .tomorrow-red, pre .variable, pre .attribute, pre .tag, pre .regexp, pre .ruby .constant, pre .xml .tag .title, pre .xml .pi, pre .xml .doctype, pre .html .doctype, pre .css .id, pre .css .class, pre .css .pseudo { 10 | color: #cc6666; 11 | } 12 | 13 | .tomorrow-orange, pre .number, pre .preprocessor, pre .built_in, pre .literal, pre .params, pre .constant { 14 | color: #de935f; 15 | } 16 | 17 | .tomorrow-yellow, pre .class, pre .ruby .class .title, pre .css .rules .attribute { 18 | color: #f0c674; 19 | } 20 | 21 | .tomorrow-green, pre .string, pre .value, pre .inheritance, pre .header, pre .ruby .symbol, pre .xml .cdata { 22 | color: #b5bd68; 23 | } 24 | 25 | .tomorrow-aqua, pre .css .hexcolor { 26 | color: #8abeb7; 27 | } 28 | 29 | .tomorrow-blue, pre .function, pre .python .decorator, pre .python .title, pre .ruby .function .title, pre .ruby .title .keyword, pre .perl .sub, pre .javascript .title, pre .coffeescript .title { 30 | color: #81a2be; 31 | } 32 | 33 | .tomorrow-purple, pre .keyword, pre .javascript .function { 34 | color: #b294bb; 35 | } 36 | 37 | pre code { 38 | display: block; 39 | background: #1d1f21; 40 | color: #c5c8c6; 41 | padding: 0.5em; 42 | } 43 | 44 | pre .coffeescript .javascript, 45 | pre .javascript .xml, 46 | pre .tex .formula, 47 | pre .xml .javascript, 48 | pre .xml .vbscript, 49 | pre .xml .css, 50 | pre .xml .cdata { 51 | opacity: 0.5; 52 | } 53 | -------------------------------------------------------------------------------- /css/fonts/Gotham/Gotham-Bold.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/calebsmith/gdi-intro-python/0caff0c7425694f1c68e0565097ec9691260a98b/css/fonts/Gotham/Gotham-Bold.otf -------------------------------------------------------------------------------- /css/fonts/Gotham/Gotham-Book.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/calebsmith/gdi-intro-python/0caff0c7425694f1c68e0565097ec9691260a98b/css/fonts/Gotham/Gotham-Book.otf -------------------------------------------------------------------------------- /css/gdicool.css: -------------------------------------------------------------------------------- 1 | @font-face { 2 | font-family: "Gotham"; 3 | src: local("Gotham"), url("fonts/Gotham/Gotham-Medium.otf") format("opentype"); 4 | font-weight: normal; 5 | font-style: normal; } 6 | 7 | @font-face { 8 | font-family: "Gotham-Book"; 9 | src: local("Gotham-Book"), url("fonts/Gotham/Gotham-Book.otf") format("opentype"); 10 | font-weight: normal; 11 | font-style: normal; } 12 | 13 | @font-face { 14 | font-family: "Gotham-Italic"; 15 | src: local("Gotham-Italic"), url("fonts/Gotham/Gotham-MediumItalic.otf") format("opentype"); 16 | font-weight: normal; 17 | font-style: italic; } 18 | 19 | @font-face { 20 | font-family: "Gotham-Bold"; 21 | src: local("Gotham-Bold"), url("fonts/Gotham/Gotham-Bold.otf") format("opentype"); 22 | font-weight: bold; 23 | font-style: bold; } 24 | 25 | /********************************************* 26 | * GLOBAL STYLES 27 | *********************************************/ 28 | 29 | .reveal footer{ 30 | position: fixed; 31 | height: 40px; 32 | width: 100%; 33 | bottom: 3px; 34 | left: 0; 35 | z-index: 0; 36 | font-size: 35%; 37 | text-align:right; 38 | background-image: url(../images/pink-logo.png); 39 | background-repeat: no-repeat; 40 | background-size: auto 100%; 41 | font-family:; 42 | } 43 | .reveal footer .copyright{ 44 | margin:15px 5px 0 100px; 45 | font-style: italic; 46 | } 47 | .reveal footer .copyright a img{ 48 | vertical-align: middle; 49 | } 50 | 51 | body { 52 | background: #e9f1da; 53 | background: -moz-radial-gradient(center, circle cover, #f7fbfc 0%, #e9f1da 100%); 54 | background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%, #f7fbfc), color-stop(100%, #e9f1da)); 55 | background: -webkit-radial-gradient(center, circle cover, #f7fbfc 0%, #e9f1da 100%); 56 | background: -o-radial-gradient(center, circle cover, #f7fbfc 0%, #e9f1da 100%); 57 | background: -ms-radial-gradient(center, circle cover, #f7fbfc 0%, #e9f1da 100%); 58 | background: radial-gradient(center, circle cover, #f7fbfc 0%, #e9f1da 100%); 59 | background-color: #92bb44; } 60 | 61 | .reveal { 62 | font-family: "Gotham-Book", "Helvetica", Arial, sans-serif; 63 | font-size: 36px; 64 | font-weight: 200; 65 | letter-spacing: -0.02em; 66 | color: #333333; } 67 | 68 | ::selection { 69 | color: white; 70 | background: #134674; 71 | text-shadow: none; } 72 | 73 | /********************************************* 74 | * HEADERS 75 | *********************************************/ 76 | .reveal h1, 77 | .reveal h2, 78 | .reveal h3, 79 | .reveal h4, 80 | .reveal h5, 81 | .reveal h6 { 82 | margin: 0 0 20px 0; 83 | color: #8b0036; 84 | font-family: "Gotham-Bold", Impact, sans-serif; 85 | line-height: 0.9em; 86 | letter-spacing: 0.02em; 87 | text-transform: uppercase; 88 | text-shadow: 0px 0px 6px rgba(0, 0, 0, 0.2); } 89 | 90 | .reveal h1 { 91 | text-shadow: 0px 0px 6px rgba(0, 0, 0, 0.2); } 92 | 93 | /********************************************* 94 | * LINKS 95 | *********************************************/ 96 | .reveal a:not(.image) { 97 | color: #01a9b4; 98 | text-decoration: none; 99 | -webkit-transition: color .15s ease; 100 | -moz-transition: color .15s ease; 101 | -ms-transition: color .15s ease; 102 | -o-transition: color .15s ease; 103 | transition: color .15s ease; } 104 | 105 | .reveal a:not(.image):hover { 106 | color: #f9b8bb; 107 | text-shadow: none; 108 | border: none; } 109 | 110 | .reveal .roll span:after { 111 | color: #fff; 112 | background: #01a9b4; } 113 | 114 | /********************************************* 115 | * IMAGES 116 | *********************************************/ 117 | .reveal section img { 118 | margin: 15px; 119 | background: rgba(255, 255, 255, 0.12); 120 | border: 4px solid #333333; 121 | box-shadow: 0 0 10px rgba(0, 0, 0, 0.15); 122 | -webkit-transition: all .2s linear; 123 | -moz-transition: all .2s linear; 124 | -ms-transition: all .2s linear; 125 | -o-transition: all .2s linear; 126 | transition: all .2s linear; } 127 | 128 | .reveal a:hover img { 129 | background: rgba(255, 255, 255, 0.2); 130 | border-color: #01a9b4; 131 | box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); } 132 | 133 | /********************************************* 134 | * NAVIGATION CONTROLS 135 | *********************************************/ 136 | .reveal .controls div.left, 137 | .reveal .controls div.left.enabled { 138 | border-right-color: #01a9b4; } 139 | 140 | .reveal .controls div.right, 141 | .reveal .controls div.right.enabled { 142 | border-left-color: #01a9b4; } 143 | 144 | .reveal .controls div.up, 145 | .reveal .controls div.up.enabled { 146 | border-bottom-color: #01a9b4; } 147 | 148 | .reveal .controls div.down, 149 | .reveal .controls div.down.enabled { 150 | border-top-color: #01a9b4; } 151 | 152 | .reveal .controls div.left.enabled:hover { 153 | border-right-color: #f9b8bb; } 154 | 155 | .reveal .controls div.right.enabled:hover { 156 | border-left-color: #f9b8bb; } 157 | 158 | .reveal .controls div.up.enabled:hover { 159 | border-bottom-color: #f9b8bb; } 160 | 161 | .reveal .controls div.down.enabled:hover { 162 | border-top-color: #f9b8bb; } 163 | 164 | /********************************************* 165 | * PROGRESS BAR 166 | *********************************************/ 167 | .reveal .progress { 168 | background: rgba(0, 0, 0, 0.2); } 169 | 170 | .reveal .progress span { 171 | background: #01a9b4; 172 | -webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); 173 | -moz-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); 174 | -ms-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); 175 | -o-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); 176 | transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); } 177 | -------------------------------------------------------------------------------- /examples/board.dat: -------------------------------------------------------------------------------- 1 | **************************** 2 | * * * 3 | * * * 4 | * * o * 5 | * * * 6 | * ^ * * 7 | * * * 8 | *********-**********-******* 9 | * ^ $ * 10 | * * 11 | * f * 12 | * * 13 | **************************** 14 | -------------------------------------------------------------------------------- /examples/boilerplate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This small program acts as a template to help you create your own programs. 4 | 5 | The first line of this file '#!/usr/bin/python' tells the operating system to 6 | use the Python program to run this file. On MacOSX and GNU/Linux, this allows 7 | the program to be run from the terminal with './boilerplate.py' rather than 8 | 'python boilerplate.py' 9 | 10 | A program using the 'if __name__ == '__main__' pattern at the bottom of this 11 | file is more reusable because it will not automatically run main() when the 12 | file is imported in another Python file. Therefore, functions and other code 13 | defined here can be used elsewhere without the risk of accidentally running 14 | code specific to this program. 15 | 16 | For example, another file can 'import boilerplate' and use 17 | 'boilerplate.example_func()'. If main() were called at the bottom of this file 18 | without the surrounding if statement, it would automatically execute when 19 | boilerplate was imported with 'import boilerplate'. 20 | 21 | This allows us to use the same Python file as a program on its own, or as Python 22 | code for other Python code to import and use. 23 | """ 24 | 25 | def example_func(x): 26 | return x + 5 27 | 28 | 29 | def main(): 30 | value = example_func(5) 31 | print('I am a placeholder for a program') 32 | print('Surely, 5 + 5 is', value) 33 | # call other functions and do meaningful work from here 34 | 35 | 36 | if __name__ == '__main__': 37 | # This block only executes if this python file is run as a program from 38 | # the command line (E.g. `python boilerplate.py`). 39 | main() 40 | 41 | -------------------------------------------------------------------------------- /examples/books.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | Suitable after taking class 4 4 | 5 | Some text processing functions that help open a plain-text book and process 6 | its lines into a collection of discreet words therein. 7 | 8 | Plain text books without copyright can be obtained from Project Gutenberg: 9 | http://www.gutenberg.org/ 10 | 11 | run 'python book.py' to see the list of words in a text file, that are not in 12 | the dictionary. 13 | 14 | The default book is "Pride and Prejudice" by Jane Austen found 15 | in pride.txt 16 | 17 | run 'python book.py a.txt' to open a different book (in this case a.txt) 18 | """ 19 | 20 | import sys 21 | from helpers import get_english_words, generate_words 22 | 23 | 24 | DEFAULT_BOOK = 'pride.txt' 25 | 26 | 27 | def main(filename): 28 | try: 29 | words_set = set(generate_words(filename)) 30 | except IOError: 31 | print('File {0} not found'.format(filename)) 32 | return 33 | english_words = get_english_words() 34 | not_in_english = words_set.difference(english_words) 35 | print('Words in {0} that are not in the dictionary:'.format(filename)) 36 | for word in sorted(list(not_in_english)): 37 | print(word) 38 | 39 | 40 | if __name__ == '__main__': 41 | help_flag = False 42 | if len(sys.argv) > 1: 43 | arg = sys.argv[1] 44 | if arg == '-h' or arg == '--help': 45 | help_flag = True 46 | print(__doc__) 47 | filename = sys.argv[1] 48 | else: 49 | filename = DEFAULT_BOOK 50 | if not help_flag: 51 | main(filename) 52 | -------------------------------------------------------------------------------- /examples/durham_establishments.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/calebsmith/gdi-intro-python/0caff0c7425694f1c68e0565097ec9691260a98b/examples/durham_establishments.csv -------------------------------------------------------------------------------- /examples/game1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This is a simple text based game that displays a board and obtains input from 4 | the command line. 5 | 6 | 7 | In this stage, the following is already implemented: 8 | * Loads a text file as the playing board 9 | * Displays the board and obtains input in a loop until a user types `quit` 10 | 11 | 12 | The following needs to be implemented: 13 | * Display the player on the board 14 | * Move the player on the board when the user types input such as "up" 15 | """ 16 | from __future__ import print_function 17 | 18 | 19 | DEFAULT_BOARD = 'board.dat' 20 | PLAYER_X_START = 5 21 | PLAYER_Y_START = 5 22 | 23 | 24 | def print_char(char): 25 | """Print only the given `char` without a newline""" 26 | print(char, end='') 27 | 28 | 29 | def get_input(): 30 | try: 31 | move = raw_input("Choose a direction (Type `quit` to quit): ") 32 | except NameError: 33 | # Python3 34 | move = input("Choose a direction (Type `quit` to quit): ") 35 | return move 36 | 37 | 38 | def load_board(filename): 39 | """ 40 | Given a filename of a text file, load the characters therein and return as 41 | a list of character lists. E.g.: 42 | 43 | A file containing: 44 | xox 45 | oxx 46 | oxo 47 | 48 | would return: 49 | [ 50 | ['x', 'o', 'x'], 51 | ['o', 'x', 'x'], 52 | ['o', 'x', 'o'], 53 | ] 54 | """ 55 | board_file = open(filename) 56 | board_tiles = [] 57 | for line in board_file.readlines(): 58 | board_tiles.append([char for char in line.strip()]) 59 | board_file.close() 60 | return board_tiles 61 | 62 | 63 | def get_tile(board, x, y): 64 | """ 65 | Returns the character for a give, `x` and `y` position of the given `board` 66 | """ 67 | return board[y][x] 68 | 69 | 70 | def display(board, player_x, player_y): 71 | """ 72 | Display the given `board` and the player at the position `player_x` and 73 | `player_y` 74 | """ 75 | for y, row in enumerate(board): 76 | for x, tile in enumerate(row): 77 | # FIXME: Insert code here to display player 78 | print_char(tile) 79 | print_char('\n') 80 | 81 | 82 | def main(): 83 | # Load the board and set the player at the starting position 84 | board = load_board(DEFAULT_BOARD) 85 | player_x = PLAYER_X_START 86 | player_y = PLAYER_Y_START 87 | while True: 88 | # Display the board and player 89 | display(board, player_x, player_y) 90 | # Obtain and handle user input 91 | move = get_input() 92 | # FIXME: Insert code here to handle the 'move' the player has made. 93 | # (Hint: should manipulate player_x and player_y) 94 | if move == 'quit': 95 | return True 96 | 97 | 98 | if __name__ == '__main__': 99 | main() 100 | -------------------------------------------------------------------------------- /examples/game2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This is a simple text based game that displays a board and obtains input from 4 | the command line. 5 | 6 | 7 | In this stage, the following is already implemented: 8 | * Loads a text file as the playing board 9 | * Displays the board and obtains input in a loop until a user types `quit` 10 | * Displays the player on the board 11 | * Moves the player on the board when the user types input such as "up" 12 | 13 | The following needs to be implemented: 14 | * Prevent the player from walking through walls 15 | """ 16 | from __future__ import print_function 17 | 18 | 19 | DEFAULT_BOARD = 'board.dat' 20 | PLAYER_X_START = 5 21 | PLAYER_Y_START = 5 22 | 23 | 24 | def print_char(char): 25 | """Print only the given `char` without a newline""" 26 | print(char, end='') 27 | 28 | 29 | def get_input(): 30 | try: 31 | move = raw_input("Choose a direction (Type `quit` to quit): ") 32 | except NameError: 33 | # Python3 34 | move = input("Choose a direction (Type `quit` to quit): ") 35 | return move 36 | 37 | 38 | def load_board(filename): 39 | """ 40 | Given a filename of a text file, load the characters therein and return as 41 | a list of character lists. E.g.: 42 | 43 | A file containing: 44 | xox 45 | oxx 46 | oxo 47 | 48 | would return: 49 | [ 50 | ['x', 'o', 'x'], 51 | ['o', 'x', 'x'], 52 | ['o', 'x', 'o'], 53 | ] 54 | """ 55 | board_file = open(filename) 56 | board_tiles = [] 57 | for line in board_file.readlines(): 58 | board_tiles.append([char for char in line.strip()]) 59 | board_file.close() 60 | return board_tiles 61 | 62 | 63 | def get_tile(board, x, y): 64 | """ 65 | Returns the character for a give, `x` and `y` position of the given `board` 66 | """ 67 | return board[y][x] 68 | 69 | 70 | def display(board, player_x, player_y): 71 | """ 72 | Display the given `board` and the player at the position `player_x` and 73 | `player_y` 74 | """ 75 | for y, row in enumerate(board): 76 | for x, tile in enumerate(row): 77 | if x == player_x and y == player_y: 78 | print_char('@') 79 | else: 80 | print_char(tile) 81 | print_char('\n') 82 | 83 | 84 | def main(): 85 | board = load_board(DEFAULT_BOARD) 86 | player_x = PLAYER_X_START 87 | player_y = PLAYER_Y_START 88 | while True: 89 | display(board, player_x, player_y) 90 | move = get_input() 91 | if move == 'quit': 92 | return True 93 | # FIXME: Make it so the player cannot walk through walls 94 | # Hint: Call get_tile to determine what is on the board at x, y 95 | if move == 'up': 96 | player_y -= 1 97 | if move == 'down': 98 | player_y += 1 99 | if move == 'left': 100 | player_x -= 1 101 | if move == 'right': 102 | player_x += 1 103 | 104 | 105 | if __name__ == '__main__': 106 | main() 107 | -------------------------------------------------------------------------------- /examples/game3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This is a simple text based game that displays a board and obtains input from 4 | the command line. 5 | 6 | 7 | In this stage, the following is already implemented: 8 | * Loads a text file as the playing board 9 | * Displays the board and obtains input in a loop until a user types `quit` 10 | * Displays the player on the board 11 | * Moves the player on the board when the user types input such as "up" 12 | * Prevents the player from walking through walls 13 | 14 | The following needs to be implemented: 15 | * Make it so the player can pick up the items (The items look like ^ and f) 16 | * Once picked up, the board should no longer display the items. 17 | * The items should appear in the player's inventory 18 | """ 19 | from __future__ import print_function 20 | 21 | 22 | DEFAULT_BOARD = 'board.dat' 23 | PLAYER_X_START = 5 24 | PLAYER_Y_START = 5 25 | 26 | NON_SOLIDS = ['^', '$', 'o', ' ', 'f'] 27 | 28 | 29 | def print_char(char): 30 | """Print only the given `char` without a newline""" 31 | print(char, end='') 32 | 33 | 34 | def get_input(): 35 | try: 36 | move = raw_input("Choose a direction (Type `quit` to quit): ") 37 | except NameError: 38 | # Python3 39 | move = input("Choose a direction (Type `quit` to quit): ") 40 | return move 41 | 42 | 43 | def load_board(filename): 44 | """ 45 | Given a filename of a text file, load the characters therein and return as 46 | a list of character lists. E.g.: 47 | 48 | A file containing: 49 | xox 50 | oxx 51 | oxo 52 | 53 | would return: 54 | [ 55 | ['x', 'o', 'x'], 56 | ['o', 'x', 'x'], 57 | ['o', 'x', 'o'], 58 | ] 59 | """ 60 | board_file = open(filename) 61 | board_tiles = [] 62 | for line in board_file.readlines(): 63 | board_tiles.append([char for char in line.strip()]) 64 | board_file.close() 65 | return board_tiles 66 | 67 | 68 | def get_tile(board, x, y): 69 | """ 70 | Returns the character for a give, `x` and `y` position of the given `board` 71 | """ 72 | return board[y][x] 73 | 74 | 75 | def display(board, player_x, player_y, player_inventory): 76 | """ 77 | Display the given `board` and the player at the position `player_x` and 78 | `player_y` 79 | """ 80 | for y, row in enumerate(board): 81 | for x, tile in enumerate(row): 82 | if x == player_x and y == player_y: 83 | print_char('@') 84 | else: 85 | print_char(tile) 86 | print_char('\n') 87 | 88 | 89 | def main(): 90 | board = load_board(DEFAULT_BOARD) 91 | player_x = PLAYER_X_START 92 | player_y = PLAYER_Y_START 93 | player_inventory = [] 94 | while True: 95 | display(board, player_x, player_y, player_inventory) 96 | print('Player inventory:') 97 | # FIXME: Print out the player's inventory here 98 | move = get_input() 99 | if move == 'quit': 100 | return True 101 | if move == 'up': 102 | if get_tile(board, player_x, player_y - 1) in NON_SOLIDS: 103 | player_y -= 1 104 | if move == 'down': 105 | if get_tile(board, player_x, player_y + 1) in NON_SOLIDS: 106 | player_y += 1 107 | if move == 'left': 108 | if get_tile(board, player_x - 1, player_y) in NON_SOLIDS: 109 | player_x -= 1 110 | if move == 'right': 111 | if get_tile(board, player_x + 1, player_y) in NON_SOLIDS: 112 | player_x += 1 113 | # FIXME: Check if the user has obtained an item (A ^ or * on the board) 114 | # Remove the item from the board if the user picks it up 115 | 116 | 117 | if __name__ == '__main__': 118 | main() 119 | -------------------------------------------------------------------------------- /examples/game4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This is a simple text based game that displays a board and obtains input from 4 | the command line. 5 | 6 | 7 | In this stage, the following is already implemented: 8 | * Loads a text file as the playing board 9 | * Displays the board and obtains input in a loop until a user types `quit` 10 | * Displays the player on the board 11 | * Moves the player on the board when the user types input such as "up" 12 | * Prevents the player from walking through walls 13 | * Makes it so the player can pick up the item (Item looks like ^) 14 | 15 | Implement the following: 16 | * Make it so the player can use the key to open the door. 17 | """ 18 | from __future__ import print_function 19 | 20 | 21 | DEFAULT_BOARD = 'board.dat' 22 | PLAYER_X_START = 5 23 | PLAYER_Y_START = 5 24 | 25 | NON_SOLIDS = ['^', '$', 'o', ' ', 'f'] 26 | 27 | 28 | def print_char(char): 29 | """Print only the given `char` without a newline""" 30 | print(char, end='') 31 | 32 | 33 | def get_input(): 34 | try: 35 | move = raw_input("Choose a direction (Type `quit` to quit): ") 36 | except NameError: 37 | # Python3 38 | move = input("Choose a direction (Type `quit` to quit): ") 39 | return move 40 | 41 | 42 | def load_board(filename): 43 | """ 44 | Given a filename of a text file, load the characters therein and return as 45 | a list of character lists. E.g.: 46 | 47 | A file containing: 48 | xox 49 | oxx 50 | oxo 51 | 52 | would return: 53 | [ 54 | ['x', 'o', 'x'], 55 | ['o', 'x', 'x'], 56 | ['o', 'x', 'o'], 57 | ] 58 | """ 59 | board_file = open(filename) 60 | board_tiles = [] 61 | for line in board_file.readlines(): 62 | board_tiles.append([char for char in line.strip()]) 63 | board_file.close() 64 | return board_tiles 65 | 66 | 67 | def get_tile(board, x, y): 68 | """ 69 | Returns the character for a give, `x` and `y` position of the given `board` 70 | """ 71 | return board[y][x] 72 | 73 | 74 | def display(board, player_x, player_y, player_inventory): 75 | """ 76 | Display the given `board` and the player at the position `player_x` and 77 | `player_y` 78 | """ 79 | for y, row in enumerate(board): 80 | for x, tile in enumerate(row): 81 | if x == player_x and y == player_y: 82 | print_char('@') 83 | else: 84 | print_char(tile) 85 | print_char('\n') 86 | 87 | 88 | def main(): 89 | board = load_board(DEFAULT_BOARD) 90 | player_x = PLAYER_X_START 91 | player_y = PLAYER_Y_START 92 | player_inventory = [] 93 | while True: 94 | display(board, player_x, player_y, player_inventory) 95 | print('Player inventory:') 96 | for item in player_inventory: 97 | print(item) 98 | move = get_input() 99 | if move == 'quit': 100 | return True 101 | if move == 'up': 102 | # FIXME: Add a check that allows the player to pass through a door 103 | # if they have a key. 104 | if get_tile(board, player_x, player_y - 1) in NON_SOLIDS: 105 | player_y -= 1 106 | if move == 'down': 107 | # FIXME: Add a check that allows the player to pass through a door 108 | # if they have a key. 109 | if get_tile(board, player_x, player_y + 1) in NON_SOLIDS: 110 | player_y += 1 111 | if move == 'left': 112 | if get_tile(board, player_x - 1, player_y) in NON_SOLIDS: 113 | player_x -= 1 114 | if move == 'right': 115 | if get_tile(board, player_x + 1, player_y) in NON_SOLIDS: 116 | player_x += 1 117 | current_tile = get_tile(board, player_x, player_y) 118 | if current_tile in ['^', 'f'] and current_tile not in player_inventory: 119 | board[player_y][player_x] = ' ' 120 | player_inventory.append(current_tile) 121 | 122 | 123 | if __name__ == '__main__': 124 | main() 125 | -------------------------------------------------------------------------------- /examples/game5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This is a simple text based game that displays a board and obtains input from 4 | the command line. 5 | 6 | 7 | In this stage, the following is already implemented: 8 | * Loads a text file as the playing board 9 | * Displays the board and obtains input in a loop until a user types `quit` 10 | * Displays the player on the board 11 | * Moves the player on the board when the user types input such as "up" 12 | * Prevents the player from walking through walls 13 | * Makes it so the player can pick up the item (Item looks like ^) 14 | * Makes it so the player can use the key to open the door. 15 | 16 | Implement the following: 17 | * Make it so the dragon (looks like $) kills you unless you have a sword 18 | * If you have a sword (looks like f) you beat the dragon 19 | * If you are on the treasure (looks like o) you win 20 | """ 21 | from __future__ import print_function 22 | 23 | 24 | DEFAULT_BOARD = 'board.dat' 25 | PLAYER_X_START = 5 26 | PLAYER_Y_START = 5 27 | 28 | NON_SOLIDS = ['^', '$', 'o', ' ', 'f'] 29 | 30 | 31 | def print_char(char): 32 | """Print only the given `char` without a newline""" 33 | print(char, end='') 34 | 35 | 36 | def get_input(): 37 | try: 38 | move = raw_input("Choose a direction (Type `quit` to quit): ") 39 | except NameError: 40 | # Python3 41 | move = input("Choose a direction (Type `quit` to quit): ") 42 | return move 43 | 44 | 45 | def load_board(filename): 46 | """ 47 | Given a filename of a text file, load the characters therein and return as 48 | a list of character lists. E.g.: 49 | 50 | A file containing: 51 | xox 52 | oxx 53 | oxo 54 | 55 | would return: 56 | [ 57 | ['x', 'o', 'x'], 58 | ['o', 'x', 'x'], 59 | ['o', 'x', 'o'], 60 | ] 61 | """ 62 | board_file = open(filename) 63 | board_tiles = [] 64 | for line in board_file.readlines(): 65 | board_tiles.append([char for char in line.strip()]) 66 | board_file.close() 67 | return board_tiles 68 | 69 | 70 | def get_tile(board, x, y): 71 | """ 72 | Returns the character for a give, `x` and `y` position of the given `board` 73 | """ 74 | return board[y][x] 75 | 76 | 77 | def display(board, player_x, player_y, player_inventory): 78 | """ 79 | Display the given `board` and the player at the position `player_x` and 80 | `player_y` 81 | """ 82 | for y, row in enumerate(board): 83 | for x, tile in enumerate(row): 84 | if x == player_x and y == player_y: 85 | print_char('@') 86 | else: 87 | print_char(tile) 88 | print_char('\n') 89 | 90 | 91 | def main(): 92 | board = load_board(DEFAULT_BOARD) 93 | player_x = PLAYER_X_START 94 | player_y = PLAYER_Y_START 95 | player_inventory = [] 96 | while True: 97 | display(board, player_x, player_y, player_inventory) 98 | print('Player inventory:') 99 | for item in player_inventory: 100 | print(item) 101 | move = get_input() 102 | next_x, next_y = player_x, player_y 103 | if move == 'quit': 104 | return 105 | elif move == 'up': 106 | next_x = player_x 107 | next_y = player_y - 1 108 | elif move == 'down': 109 | next_x = player_x 110 | next_y = player_y + 1 111 | elif move == 'left': 112 | next_x = player_x - 1 113 | next_y = player_y 114 | elif move == 'right': 115 | next_x = player_x + 1 116 | next_y = player_y 117 | next_tile = get_tile(board, next_x, next_y) 118 | if next_tile in NON_SOLIDS or '^' in player_inventory and next_tile == '-': 119 | player_x = next_x 120 | player_y = next_y 121 | current_tile = get_tile(board, player_x, player_y) 122 | if current_tile in ['^', 'f'] and current_tile not in player_inventory: 123 | board[player_y][player_x] = ' ' 124 | player_inventory.append(current_tile) 125 | if current_tile == '-' and '^' in player_inventory: 126 | board[player_y][player_x] = ' ' 127 | player_inventory.remove('^') 128 | 129 | 130 | if __name__ == '__main__': 131 | main() 132 | -------------------------------------------------------------------------------- /examples/game6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This is a simple text based game that displays a board and obtains input from 4 | the command line. 5 | 6 | 7 | In this stage, the following is already implemented: 8 | * Loads a text file as the playing board 9 | * Displays the board and obtains input in a loop until a user types `quit` 10 | * Displays the player on the board 11 | * Moves the player on the board when the user types input such as "up" 12 | * Prevents the player from walking through walls 13 | * Makes it so the player can pick up the item (Item looks like ^) 14 | * Makes it so the player can use the key to open the door. 15 | * Makes it so the dragon (looks like $) kills you unless you have a sword 16 | * If you have a sword (looks like f) you beat the dragon 17 | * If you are on the treasure (looks like o) you win 18 | 19 | To implement: 20 | * Make a Board class to improve the load, get_tile related code 21 | """ 22 | from __future__ import print_function 23 | 24 | 25 | DEFAULT_BOARD = 'board.dat' 26 | PLAYER_X_START = 5 27 | PLAYER_Y_START = 5 28 | 29 | NON_SOLIDS = ['^', '$', 'o', ' ', 'f'] 30 | 31 | 32 | def print_char(char): 33 | """Print only the given `char` without a newline""" 34 | print(char, end='') 35 | 36 | 37 | def get_input(): 38 | try: 39 | move = raw_input("Choose a direction (Type `quit` to quit): ") 40 | except NameError: 41 | # Python3 42 | move = input("Choose a direction (Type `quit` to quit): ") 43 | return move 44 | 45 | 46 | def load_board(filename): 47 | """ 48 | Given a filename of a text file, load the characters therein and return as 49 | a list of character lists. E.g.: 50 | 51 | A file containing: 52 | xox 53 | oxx 54 | oxo 55 | 56 | would return: 57 | [ 58 | ['x', 'o', 'x'], 59 | ['o', 'x', 'x'], 60 | ['o', 'x', 'o'], 61 | ] 62 | """ 63 | board_file = open(filename) 64 | board_tiles = [] 65 | for line in board_file.readlines(): 66 | board_tiles.append([char for char in line.strip()]) 67 | board_file.close() 68 | return board_tiles 69 | 70 | 71 | def get_tile(board, x, y): 72 | """ 73 | Returns the character for a give, `x` and `y` position of the given `board` 74 | """ 75 | return board[y][x] 76 | 77 | 78 | def display(board, player_x, player_y, player_inventory): 79 | """ 80 | Display the given `board` and the player at the position `player_x` and 81 | `player_y` 82 | """ 83 | for y, row in enumerate(board): 84 | for x, tile in enumerate(row): 85 | if x == player_x and y == player_y: 86 | print_char('@') 87 | else: 88 | print_char(tile) 89 | print_char('\n') 90 | 91 | 92 | def main(): 93 | board = load_board(DEFAULT_BOARD) 94 | player_x = PLAYER_X_START 95 | player_y = PLAYER_Y_START 96 | player_inventory = [] 97 | while True: 98 | display(board, player_x, player_y, player_inventory) 99 | print('Player inventory:') 100 | for item in player_inventory: 101 | print(item) 102 | move = get_input() 103 | next_x, next_y = player_x, player_y 104 | if move == 'quit': 105 | return 106 | elif move == 'up': 107 | next_x = player_x 108 | next_y = player_y - 1 109 | elif move == 'down': 110 | next_x = player_x 111 | next_y = player_y + 1 112 | elif move == 'left': 113 | next_x = player_x - 1 114 | next_y = player_y 115 | elif move == 'right': 116 | next_x = player_x + 1 117 | next_y = player_y 118 | next_tile = get_tile(board, next_x, next_y) 119 | if next_tile in NON_SOLIDS or '^' in player_inventory and next_tile == '-': 120 | player_x = next_x 121 | player_y = next_y 122 | current_tile = get_tile(board, player_x, player_y) 123 | if current_tile in ['^', 'f'] and current_tile not in player_inventory: 124 | board[player_y][player_x] = ' ' 125 | player_inventory.append(current_tile) 126 | if current_tile == '-' and '^' in player_inventory: 127 | board[player_y][player_x] = ' ' 128 | player_inventory.remove('^') 129 | if current_tile == '$': 130 | board[player_y][player_x] = ' ' 131 | if 'f' not in player_inventory: 132 | print("You are defenseless and the dragon defeats you") 133 | return 134 | print("You defeat the dragon with your sword") 135 | if current_tile == 'o': 136 | print("You obtain the sweet sweet treasures. YOU WIN!") 137 | return 138 | 139 | 140 | if __name__ == '__main__': 141 | main() 142 | -------------------------------------------------------------------------------- /examples/game7.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This is a simple text based game that displays a board and obtains input from 4 | the command line. 5 | 6 | 7 | In this stage, the following is already implemented: 8 | * Loads a text file as the playing board 9 | * Displays the board and obtains input in a loop until a user types `quit` 10 | * Displays the player on the board 11 | * Moves the player on the board when the user types input such as "up" 12 | * Prevents the player from walking through walls 13 | * Makes it so the player can pick up the item (Item looks like ^) 14 | * Makes it so the player can use the key to open the door. 15 | * Makes it so the dragon (looks like $) kills you unless you have a sword 16 | * If you have a sword (looks like f) you beat the dragon 17 | * If you are on the treasure (looks like o) you win 18 | * Makes a Board class to clean up board code 19 | """ 20 | from __future__ import print_function 21 | 22 | 23 | DEFAULT_BOARD = 'board.dat' 24 | PLAYER_X_START = 5 25 | PLAYER_Y_START = 5 26 | 27 | NON_SOLIDS = ['^', '$', 'o', ' ', 'f'] 28 | 29 | 30 | def print_char(char): 31 | """Print only the given `char` without a newline""" 32 | print(char, end='') 33 | 34 | 35 | def get_input(): 36 | try: 37 | move = raw_input("Choose a direction (Type `quit` to quit): ") 38 | except NameError: 39 | # Python3 40 | move = input("Choose a direction (Type `quit` to quit): ") 41 | return move 42 | 43 | 44 | class Board(object): 45 | 46 | def __init__(self, filename): 47 | """ 48 | Given a filename of a text file, load the characters therein and store 49 | the board data internally as a list of character lists. E.g.: 50 | 51 | A file containing: 52 | xox 53 | oxx 54 | oxo 55 | 56 | would store as: 57 | [ 58 | ['x', 'o', 'x'], 59 | ['o', 'x', 'x'], 60 | ['o', 'x', 'o'], 61 | ] 62 | """ 63 | board_file = open(filename) 64 | board_tiles = [] 65 | for line in board_file.readlines(): 66 | board_tiles.append([char for char in line.strip()]) 67 | board_file.close() 68 | self.tiles = board_tiles 69 | 70 | def get_tile(self, x, y): 71 | """ 72 | Returns the character for a give, `x` and `y` position on the board 73 | """ 74 | return self.tiles[y][x] 75 | 76 | def set_tile(self, x, y, value): 77 | """ 78 | Set the tile at `x` and `y` to `value` 79 | """ 80 | self.tiles[y][x] = value 81 | 82 | def display(self, player_x, player_y, player_inventory): 83 | """ 84 | Display the given `board` and the player at the position `player_x` and 85 | `player_y` 86 | """ 87 | for y, row in enumerate(self.tiles): 88 | for x, tile in enumerate(row): 89 | if x == player_x and y == player_y: 90 | print_char('@') 91 | else: 92 | print_char(tile) 93 | print_char('\n') 94 | 95 | 96 | def main(): 97 | board = Board(DEFAULT_BOARD) 98 | player_x = PLAYER_X_START 99 | player_y = PLAYER_Y_START 100 | player_inventory = [] 101 | while True: 102 | board.display(player_x, player_y, player_inventory) 103 | print('Player inventory:') 104 | for item in player_inventory: 105 | print(item) 106 | move = get_input() 107 | next_x, next_y = player_x, player_y 108 | if move == 'quit': 109 | return 110 | elif move == 'up': 111 | next_x = player_x 112 | next_y = player_y - 1 113 | elif move == 'down': 114 | next_x = player_x 115 | next_y = player_y + 1 116 | elif move == 'left': 117 | next_x = player_x - 1 118 | next_y = player_y 119 | elif move == 'right': 120 | next_x = player_x + 1 121 | next_y = player_y 122 | next_tile = board.get_tile(next_x, next_y) 123 | if next_tile in NON_SOLIDS or '^' in player_inventory and next_tile == '-': 124 | player_x = next_x 125 | player_y = next_y 126 | current_tile = board.get_tile(player_x, player_y) 127 | if current_tile in ['^', 'f'] and current_tile not in player_inventory: 128 | board.set_tile(player_x, player_y, ' ') 129 | player_inventory.append(current_tile) 130 | if current_tile == '-' and '^' in player_inventory: 131 | board.set_tile(player_x, player_y, ' ') 132 | player_inventory.remove('^') 133 | if current_tile == '$': 134 | board.set_tile(player_x, player_y, ' ') 135 | if 'f' not in player_inventory: 136 | print("You are defenseless and the dragon defeats you") 137 | return 138 | print("You defeat the dragon with your sword") 139 | if current_tile == 'o': 140 | print("You obtain the sweet sweet treasures. YOU WIN!") 141 | return 142 | 143 | 144 | if __name__ == '__main__': 145 | main() 146 | -------------------------------------------------------------------------------- /examples/geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | Suitable for hacking after class 2. 4 | 5 | This program demostrates using some functions to solve geometric formulas. 6 | 7 | It takes 4 arguments which are takens as two pairs of {x, y} coordinates. 8 | 9 | The program outputs the area of a rectangle formed by those points as two of 10 | its corners as well as the length of the line that intersects those two points 11 | """ 12 | 13 | import sys 14 | from math import sqrt 15 | 16 | 17 | def absolute_difference(value_a, value_b): 18 | return abs(value_a - value_b) 19 | 20 | 21 | def get_hypotenuse(a, b): 22 | return sqrt(a ** 2 + b ** 2) 23 | 24 | 25 | def get_area_rectangle(width, height): 26 | return width * height 27 | 28 | 29 | def print_area_and_hypotenuse(x1, y1, x2, y2): 30 | width = absolute_difference(x1, x2) 31 | height = absolute_difference(y1, y2) 32 | area = get_area_rectangle(width, height) 33 | hypotenuse = get_hypotenuse(width, height) 34 | print('Area of the rectangle is:') 35 | print(area) 36 | print('The diagonal of the rectangle is:') 37 | print(hypotenuse) 38 | 39 | 40 | if __name__ == '__main__': 41 | if len(sys.argv) == 5: 42 | x1, y1, x2, y2 = map(int, sys.argv[1:5]) 43 | print_area_and_hypotenuse(x1, y1, x2, y2) 44 | else: 45 | print(__doc__) 46 | print('') 47 | print('This program requires exactly 4 number arguments') 48 | 49 | -------------------------------------------------------------------------------- /examples/helpers.py: -------------------------------------------------------------------------------- 1 | #/usr/bin/python 2 | """ 3 | Suitable for hacking after class 3. 4 | 5 | This file contains functions to help you open and process text files 6 | 7 | It also provides a function for obtaining the set of English words. This can be 8 | used to help with anything you might want to do with spell-checking or 9 | determing if a word is valid according to the dictionary. 10 | 11 | N.B. The dictionary isn't necessarily exhaustive and isn't meant to be 12 | authoritative, just a useful example to work with. 13 | 14 | """ 15 | 16 | import string 17 | import sys 18 | 19 | if sys.version_info >= (3, 0): 20 | PY3 = True 21 | else: 22 | PY3 = False 23 | 24 | # Punctuation characters other than hyphen and apostrophe 25 | PUNCTUATION_CHARS = string.punctuation.replace('-', '').replace("'", '') 26 | 27 | 28 | def file_reader(filename): 29 | """ 30 | Given a filename, yields each line in the file 31 | """ 32 | with open(filename, 'r') as f: 33 | for line in f: 34 | yield line.strip() 35 | 36 | 37 | def remove_punctuation(line): 38 | """ 39 | Given a string, remove punctuation characters other than - or ' and return 40 | the resulting string 41 | """ 42 | if PY3: 43 | return line.translate(str.maketrans('', '', PUNCTUATION_CHARS)) 44 | else: 45 | return line.translate(string.maketrans('', ''), PUNCTUATION_CHARS) 46 | 47 | 48 | def generate_cleaned_lines(filename): 49 | """ 50 | Given a filename, yields each line of the file without punctuation 51 | """ 52 | return ( 53 | remove_punctuation(line.replace('--', ' ')) 54 | for line in file_reader(filename) 55 | ) 56 | 57 | 58 | def generate_words(filename): 59 | """ 60 | Given a filename, generates every word of the file in lowercase, stripping 61 | any whitespace or punctuation. Numbers are also removed 62 | """ 63 | cleaned_lines = generate_cleaned_lines(filename) 64 | return ( 65 | word.lower() 66 | for line in cleaned_lines for word in line.split() 67 | if not word.isdigit() and not word.startswith("'") 68 | ) 69 | 70 | 71 | def get_words_list(filename): 72 | """ 73 | Given a filename, returns a list of words in that file, using the same 74 | stripping rules as generate_words() 75 | """ 76 | return list(generate_words(filename)) 77 | 78 | 79 | def get_english_words(): 80 | """Returns the set of English words in lower-case""" 81 | return set(word.strip().lower() for word in file_reader('english.txt')) 82 | -------------------------------------------------------------------------------- /examples/knights.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example from class2 3 | """ 4 | 5 | def shrubbery(): 6 | print("I am a shrubber") 7 | 8 | 9 | def ni(): 10 | print("Ni!" * 3) 11 | -------------------------------------------------------------------------------- /examples/mobile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | Supplements class 4 material. 4 | 5 | The classes in this module demonstrate a simple example of using inheritance 6 | and composition 7 | """ 8 | 9 | from __future__ import print_function 10 | 11 | 12 | class Mobile(object): 13 | """ 14 | An object with an x, y position, and methods for moving 15 | """ 16 | 17 | def __init__(self, x, y): 18 | self.x = x 19 | self.y = y 20 | 21 | def move_up(self): 22 | self.y = self.y - 1 23 | 24 | def move_down(self): 25 | self.y = self.y + 1 26 | 27 | def move_left(self): 28 | self.x = self.x - 1 29 | 30 | def move_right(self): 31 | self.x = self.x + 1 32 | 33 | def __repr__(self): 34 | return "" 35 | 36 | 37 | class BoundedMobile(Mobile): 38 | """ 39 | An object with an x, y position, and methods for moving 40 | The x, y position must be within bounds 41 | 42 | N.B. This class inherits from Mobile and demonstrate how to override methods 43 | """ 44 | 45 | def __init__(self, x, y, x_limit, y_limit): 46 | """ 47 | Takes the arguments x, y, x_limit, and y_limit, where x and y represent 48 | the current position of the mobile, while x_limit and y_limit represent 49 | the upper bounds of the grid they reside on. (0, 0 is assumed as lower 50 | bounds). 51 | """ 52 | self.x = x 53 | self.y = y 54 | self.x_limit = x_limit 55 | self.y_limit = y_limit 56 | 57 | def move_up(self): 58 | # call the move_up method from the parent class (Mobile) 59 | super(BoundedMobile, self).move_up() 60 | if self.y < 0: 61 | self.y = 0 62 | 63 | def move_down(self): 64 | # call the move_up method from the parent class (Mobile) 65 | super(BoundedMobile, self).move_down() 66 | if self.y > self.y_limit: 67 | self.y = self.y_limit 68 | 69 | def move_left(self): 70 | # call the move_up method from the parent class (Mobile) 71 | super(BoundedMobile, self).move_left() 72 | if self.x < 0: 73 | self.x = 0 74 | 75 | def move_right(self): 76 | # call the move_up method from the parent class (Mobile) 77 | super(BoundedMobile, self).move_right() 78 | if self.x > self.x_limit: 79 | self.x = self.x_limit 80 | 81 | 82 | class Grid(object): 83 | """ 84 | A grid represents a gameboard or other grid pattern that holds mobiles 85 | in each tile. Multiple mobiles can exist on the same tile. 86 | """ 87 | 88 | def __init__(self, x_limit, y_limit): 89 | self.x_limit = x_limit 90 | self.y_limit = y_limit 91 | self.mobiles = {} 92 | 93 | def add_mobile(self, x, y): 94 | """ 95 | Given x, y, create a BoundedMobile instance and place it in the x, y 96 | position in the grid 97 | """ 98 | # Create a bounded mobile at the position x, y 99 | mob = BoundedMobile(x, y, self.x_limit, self.y_limit) 100 | # Obtain the list of mobiles in the position x, y 101 | mobs = self.mobiles.get((x, y), []) 102 | # Add the new mobile to that list of mobiles 103 | mobs.append(mob) 104 | self.mobiles[(x, y)] = mobs 105 | 106 | def display_mobiles(self): 107 | """ 108 | Prints the number of mobiles at each position that's occupied 109 | """ 110 | for (x, y), mobiles in self.mobiles.iteritems(): 111 | print("Position " + str(x) + ", " + str(y) + " has " + str(len(mobiles))) 112 | 113 | def display_grid(self): 114 | """ 115 | Prints a display of the grid with the number of mobiles in each position 116 | """ 117 | for y in xrange(0, self.y_limit): 118 | print('-' * self.x_limit * 3 + 1) 119 | current_row = '|' 120 | for x in xrange(0, self.x_limit): 121 | num_mobiles_in_tile = len(self.mobiles.get((x, y), [])) 122 | spacer = ' ' if num_mobiles_in_tile < 10 else '' 123 | display_value = spacer + str(num_mobiles_in_tile) 124 | current_row += display_value + '|' 125 | print(current_row) 126 | print('-' * self.x_limit * 3 + 1) 127 | 128 | def __repr__(self): 129 | return "" 130 | -------------------------------------------------------------------------------- /images/cc-license.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/calebsmith/gdi-intro-python/0caff0c7425694f1c68e0565097ec9691260a98b/images/cc-license.png -------------------------------------------------------------------------------- /images/gdi_logo_badge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/calebsmith/gdi-intro-python/0caff0c7425694f1c68e0565097ec9691260a98b/images/gdi_logo_badge.png -------------------------------------------------------------------------------- /images/pink-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/calebsmith/gdi-intro-python/0caff0c7425694f1c68e0565097ec9691260a98b/images/pink-logo.png -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Intro to Python ~ Girl Develop It 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 |
33 | 34 |
35 | 36 |
37 | 38 |

Intro to Python

39 | Revision 1 (Summer 2013) 40 | Revision 2 (Spring 2014) 41 | CityCamp RDU Session 42 |
43 | About 44 |
45 |
46 |
47 |
48 | 52 |
53 |
54 | 55 | 56 | 57 | 58 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | livereload==2.1.0 2 | -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | A server that works with the livereload chrome extension to automatically 4 | refresh the browser whenver a set of files changes. The server degrades to a 5 | SimpleHTTPServer w/o livereload capability if the livereload Python package is 6 | not available. 7 | 8 | The default port is 8000. Supply a commandline argument for a different port. 9 | 10 | This serves files from the current directory on your local browser and is good 11 | for viewing slides easily. 12 | 13 | Usage: 14 | 15 | python server.py 16 | 17 | or 18 | 19 | python server.py 20 | """ 21 | 22 | import sys 23 | import BaseHTTPServer 24 | from SimpleHTTPServer import SimpleHTTPRequestHandler 25 | 26 | HandlerClass = SimpleHTTPRequestHandler 27 | ServerClass = BaseHTTPServer.HTTPServer 28 | Protocol = "HTTP/1.0" 29 | SERVER_ADDRESS = '127.0.0.1' 30 | 31 | try: 32 | from livereload import Server as LiveServer 33 | except ImportError: 34 | LiveServer = None 35 | 36 | 37 | DEFAULT_PORT = 8000 38 | patterns = [ 39 | '*/*.html', 40 | '**/*.md', 41 | '*/images/', 42 | '*/css/', 43 | ] 44 | 45 | 46 | def main(port): 47 | if LiveServer is not None: 48 | live_reload_server(port) 49 | else: 50 | print("Using SimpleHTTPServer. Follow the README for livereload if " 51 | "desired") 52 | simple_server(port) 53 | 54 | 55 | def simple_server(port): 56 | HandlerClass.protocol_version = Protocol 57 | httpd = ServerClass((SERVER_ADDRESS, port), HandlerClass) 58 | sa = httpd.socket.getsockname() 59 | print("Serving HTTP on", sa[0], "port", sa[1], "...") 60 | httpd.serve_forever() 61 | 62 | 63 | def live_reload_server(port): 64 | server = LiveServer() 65 | for pattern in patterns: 66 | server.watch(pattern) 67 | server.serve(port=port) 68 | 69 | 70 | if __name__ == '__main__': 71 | port = int(sys.argv[1]) if sys.argv[1:] else 8000 72 | main(port) 73 | -------------------------------------------------------------------------------- /set1/class1.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Intro to Python ~ Girl Develop It 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 30 | 31 |
32 | 33 |
34 | 35 |
36 | 37 |

Intro to Python

38 |

Class 1

39 |
40 | 41 | 42 |
43 |

Welcome!

44 |
45 |

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

46 |

Some "rules"

47 |
    48 |
  • We are here for you!
  • 49 |
  • Every question is important
  • 50 |
  • Help each other
  • 51 |
  • Have fun
  • 52 |
53 |
54 |
55 | 56 |
57 |

What we will cover today

58 |
    59 |
  • Why Python?
  • 60 |
  • What is programming?
  • 61 |
  • Variables and arithmetic
  • 62 |
  • Statements and Error Messages
  • 63 |
  • Development Environment Setup
  • 64 |
65 |
66 | 67 | 68 |
69 |

Why Python?

70 |
    71 |
  • Suitable for beginners, yet used by professionals
  • 72 |
  • Readable, maintainable code
  • 73 |
  • Rapid rate of development
  • 74 |
  • Few "magical" side-effects
  • 75 |
  • Variety of applications
  • 76 |
77 |
78 | 79 |
80 |

What is Python used for?

81 |
    82 |
  • System Administration (Fabric, Salt, Ansible)
  • 83 |
  • 3D animation and image editing (Maya, Blender, Gimp)
  • 84 |
  • Scientific computing (numpy, scipy)
  • 85 |
  • Web development (Django, Flask)
  • 86 |
  • Game Development (Civilization 4, EVE Online)
  • 87 |
88 |
89 | 90 |
91 |

Who is using Python?

92 |
    93 |
  • Disney
  • 94 |
  • Dropbox
  • 95 |
  • Canonical and Red Hat
  • 96 |
  • Google
  • 97 |
  • NASA
  • 98 |
99 |
100 | 101 |
102 |

What is programming?

103 |
    104 |
  • Teaching the computer to do a task
  • 105 |
  • A program is made of one or more files of code, each of which solve part of the overall task
  • 106 |
  • Programming code is human readable but also needs a form that the computer can run directly. This form is not human readable.
  • 107 |
  • To create the form of code the computer can use, we use the Python interpreter. Other languages use other interpreters or a compiler
  • 108 |
  • Don't focus on what's "under the hood" for now. We will "drive the car" first
  • 109 |
  • In other words, there are many layers to the onion. We start at one layer and slowly move toward layers that are beneath or above us
  • 110 |
111 |
112 | 113 |
114 |

Command line, Python Shell, Text Editors

115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 |
TerminalA program that has a command line interface and issues commands to the operating system.
Python ShellA command line program that runs inside of the terminal, takes Python code as input, interprets it, and prints out any results.
Text EditorA program that opens text files and allows the user to edit and save them. (Different than a word processor).
129 |
130 | 131 |
132 |

Example Text Editors

133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 |
LinuxGedit, Jedit, Kate
MacOSXTextMate, TextWrangler
WindowsNotepad++
AllSublime Text, Vim, Emacs
151 |
152 | 153 | 154 |
155 |

Let's Develop It

156 |

Let's setup our computer for Python programming

157 |
    158 |
  • 159 | Let's install a text editor - 160 | Install Sublime Text 2 161 |
  • 162 |
  • 163 | Install Python 164 | (This step is for Windows users only. GNU/Linux and MacOSX come with Python installed) 165 |
  • 166 |
  • 167 | (Windows only): After installing Python, open the "powershell" program and type: 168 |
    [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
    169 |
  • 170 |
  • 171 | Locate and run the terminal program. Type 'python' and hit enter. 172 |
  • 173 |
  • 174 | More setup instructions are available: 175 | here 176 | (You can, but don't have to install the other text editors recommended in this guide) 177 |
  • 178 |
179 |
180 | 181 |
182 |

Working in the Python Shell

183 |

Open up your terminal and type 'python'

184 |

Follow along with the examples in the slides. Type them in!

185 |

Feel free to explore as well. You will not accidentally break things

186 |
187 | 188 |
189 |

Variables and Arithmetic

190 |

191 | 3 + 4
192 | 2 * 4
193 | 6 - 2
194 | 4 / 2
195 |                     
196 |

197 | a = 2
198 | b = 3
199 | print a + b
200 | c = a + b
201 | print c * 2
202 |                     
203 |

204 | a = 0
205 | a = a + .5
206 | print a
207 |                     
208 |
209 | 210 |
211 |

Strings

212 |

213 | a = 'Hello '
214 | b = 'World'
215 | c = a + b
216 | print c
217 |                     
218 |

219 | a = "Spam "
220 | b = a * 4
221 | print b
222 |                     
223 |

224 | a = 'spam '
225 | b = 'eggs'
226 | c = a * 4 + b
227 | print c
228 |                     
229 |
230 | 231 |
232 |

Data types

233 |
    234 |
  • Variables are names of objects
  • 235 |
  • Among other things, variables are used to represent something that can't be known until the program is run
  • 236 |
  • Objects always have a "type"
  • 237 |
  • The type of an object helps define what it can do
  • 238 |
  • The type can be found using: `type()`
  • 239 |
  • type() is a function. We call it by using parenthesis and pass it an object by placing the object inside the parenthesis
  • 240 |
241 |

242 | a = 4
243 | print type(a)
244 | print type(4)
245 | 
246 | print type(3.14)
247 | 
248 | b = 'spam, again'
249 | print type(b)
250 | print type("But I don't like spam")
251 |                     
252 |
253 | 254 |
255 |

Data types - continued ...

256 |
    257 |
  • Objects can be used with a set of operators
  • 258 |
  • An int or float can be used with any of: +, -, *, /
  • 259 |
  • A string can be used with any of: +, *
  • 260 |
  • What happens if we try to use division or subtraction with a string?
  • 261 |
262 |

263 | print "Spam" - "am"
264 | a = 'Spam and eggs'
265 | print a / 'hashbrowns'
266 | print a / 6
267 |                     
268 |
269 | 270 |
271 |

Errors

272 |
    273 |
  • There are different kinds of errors that can occur. We've seen a few of these so far
  • 274 |
  • A runtime error results in an Exception of which there are several types. Each type gives us some information about the nature of the error and how to correct it
  • 275 |
  • One type of exception is a SyntaxError. This results when our code can not be evaluated because it is incorrect at a syntactic level. In other words, we are not following the "rules" of the language.
  • 276 |
  • Some other examples are the TypeError and NameError exceptions.
  • 277 |
278 |
279 | 280 |
281 |

Errors - continued ...

282 |

283 | # SyntaxError - Doesn't conform to the rules of Python. This statement isn't meaningful to the computer
284 | 4spam)eggs(garbage) + 10
285 | 
286 | # NameError - Using a name that hasn't been defined yet
287 | a = 5
288 | print b
289 | b = 10
290 | 
291 | # TypeError - Using an object in a way that its type does not support
292 | 'string1' - 'string2'
293 |                     
294 |

There are also semantic errors. These are harder to catch because the computer can't catch them for us.

295 |
296 | 297 | 298 |
299 |

Let's Develop It

300 |

We'll practice what we've learned in the shell

301 |

Review the slides on your computer and practice entering any commands you didn't fully understand before

302 |

Ask the teacher or a TA for any help

303 |
304 | 305 | 306 | 307 |
308 |

Using the Terminal

309 |

Try each of the following commands in turn:

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 |
CommandShort forDescription
pwdPrint working directoryDisplays what folder you are in.
lsListLists the files and folders in the current folder
cdChange directoryChange to another folder. Takes the folder name as an argument. 'cd ..' goes up a directory
catConcatenatePrints the contents of a file. Takes a filename as an argument
337 |
338 | 339 |
340 |

Creating a folder

341 |

We need a folder to save our work in.

342 |

The ->'s below indicate the expected output of the previous command.

343 |

344 | pwd
345 | -> /home/username
346 | mkdir Projects
347 | cd Projects
348 | mkdir gdi-intro-python
349 | cd gdi-intro-python
350 | pwd
351 | -> /home/username/Projects/gdi-intro-python
352 |                     
353 |

Now that the folders are made, we only have to use 'cd Projects/gdi-intro-python' in the future.

354 |
355 | 356 |
357 |

The Text Editor

358 |

Open sublime text.

359 |
    360 |
  • Click file, open folder. Navigate to the gdi-intro-python folder we created and click "open"
  • 361 |
  • In the text editor, enter the following: 362 |
    
    363 | print 'I am a Python program'
    364 |                     
    365 |
  • 366 |
  • Click file, save as. Type 'class1.py' and click ok.
  • 367 |
  • Open a terminal and navigate to the gdi-intro-python folder (if not left open from before)
  • 368 |
  • Type 'python class1.py'
  • 369 |
  • You should see the terminal print "I am a Python program"
  • 370 |
371 |
372 | 373 |
374 |

User Input

375 |

To obtain user input, use 'raw_input()'

376 |

Change the class1.py text to the following and run it again

377 |

378 | input_value = raw_input("Enter a radius:")
379 | radius = float(input_value)
380 | area = 3.14159 * radius ** 2
381 | print "The area of a circle with radius " + input_value + " is:"
382 | print area
383 |                     
384 |

N.B. - The user's input is a string so we use float() to make it a number

385 |
386 | 387 | 388 |
389 |

Let's Develop It

390 |

Write your own program that uses raw_input and does something else with the value

391 |

You can use float() to treat the input as a number if you need a number, or use the input directly as a string

392 |
393 | 394 |
395 |

Questions?

396 |
397 |
398 |
399 |
400 | 404 |
405 |
406 | 407 | 408 | 409 | 410 | 433 | 434 | 435 | 436 | -------------------------------------------------------------------------------- /set1/class2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Intro to Python ~ Girl Develop It 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 |
33 | 34 |
35 | 36 |
37 | 38 |

Intro to Python

39 |

Class 2

40 |
41 | 42 | 43 |
44 |

Review

45 |
    46 |
  • Arithmetic and variables
  • 47 |
  • Data types
  • 48 |
  • Text editor, command line, and python shell
  • 49 |
50 |
51 | 52 |
53 |

What we will cover today

54 |
    55 |
  • Boolean Expressions and Conditionals
  • 56 |
  • Loops
  • 57 |
  • Functions
  • 58 |
59 |
60 | 61 |
62 |

Boolean Expressions

63 |

We can tell the computer to compare values and return True or False. These are called Boolean expressions

64 |
    65 |
  • Test for equality by using `==`. We can't use `=` because that is used for assignment
  • 66 |
  • Test for greater than and less than using `>` and `<`
  • 67 |
68 |

 69 | a = 5
 70 | b = 5
 71 | print a == b
 72 | # Combine comparison and assignment
 73 | c = a == b
 74 | print c
 75 | 
 76 | print 3 < 5
 77 |                     
78 |
79 | 80 |
81 |

Boolean Expressions continued

82 |

The following chart shows the various Boolean operators

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 |
a == ba is equal to b
a != ba does not equal b
a < ba is less than b
a > ba is greater than b
a <= ba is less than or equal to b
a >= ba is greater than or equal to b
109 |

110 | a = 3
111 | b = 4
112 | print a != b
113 | print a <= 3
114 | print a >= 4
115 |                     
116 |

Remember: Equals does not equal "equals equals"

117 |
118 | 119 |
120 |

Conditionals

121 |

When we want different code to execute dependending on certain criteria, we use a conditional

122 |

We achieve this using if statements

123 |

124 | if x == 5:
125 |     print 'x is equal to 5'
126 |                     
127 |

We often want a different block to execute if the statement is false. This can be accomplished using else

128 |

129 | if x == 5:
130 |     print 'x is equal to 5'
131 | else:
132 |     print 'x is not equal to 5'
133 |                     
134 |
135 | 136 |
137 |

Indentation

138 |

In Python, blocks begin when text is indented and ends when it returns to the previous indentation

139 |

Let's look at the previous example again with a few minor changes and examine the meaning of its indentation

140 |

141 | if x == 5:
142 |     print 'x is equal to 5'
143 |     x_is_5 = True
144 |     print 'Still in the x == 5 block'
145 | else:
146 |     print 'x is not equal to 5'
147 |     x_is_5 = False
148 |     print 'Still in the else block of x == 5'
149 | print 'Outside of the if or else blocks.'
150 | print 'x_is_5:'
151 | print x_is_5
152 |                     
153 |
154 | 155 |
156 |

Predicates

157 |

The expression after `if` and before the colon is a Boolean expression, also called a predicate

158 |

A variable can be used to store the evaluation of a predicate, especially if it is particularly long or complicated

159 |

Predicates can be combined or prefaced with Logical operators: `not`, `and` and `or`

160 |

Predicates and the logical operators that act on them can be wrapped in parenthesis to enforce prescendence

161 |
162 | 163 |
164 |

Predicates continued

165 |

The following shows some examples of combining these techniques:

166 |

167 | # 1. Simple check of two variables
168 | if x != 0 or y != 0:
169 |     print 'The point x,y is not on the x or y axis'
170 | 
171 | # 2. Checking for Pong paddle missing the ball for player 2
172 | if ball_right_x > paddle_left_x and (ball_top_y > paddle_bottom_y or ball_bottom_y < paddle_top_y):
173 |     player_1_score += 1
174 | 
175 | # The second example is a little long, we should simplify it
176 | ball_above_paddle = ball_bottom_y < paddle_top_y
177 | ball_below_paddle = ball_top_y > paddle_bottom_y
178 | ball_right_paddle = ball_right_x > paddle_left_x
179 | 
180 | if ball_right_paddle and (ball_above_paddle or ball_below_paddle):
181 |     player_1_score += 1
182 |                     
183 |
184 | 185 |
186 |

Chained conditionals

187 |

Conditionals can also be chained

188 |

Chained conditionals use elif as an additonal check after the preceeding `if` predicate was False. For example

189 |

190 | if x > 5:
191 |     print 'x is greater than 5'
192 | elif x < 5:
193 |     print 'x is less than 5'
194 | else:
195 |     print 'x is equal to 5'
196 |                     
197 |
198 | 199 |
200 |

Nested conditionals

201 |

Conditionals can also be nested

202 |

Nested conditionals occur inside of other conditionals and are indented over once more. When the code block is complete, they are unindented

203 |

204 | if x > 5:
205 |     print 'x is greater than 5'
206 |     if x > 10:
207 |         print '...it is also greater than 10'
208 |     print 'Done evaluating the x > 10 block'
209 | print 'Done evaluating the x > 5 block'
210 |                     
211 |
212 | 213 | 214 |
215 |

Let's Develop It

216 |

Write a program that uses if statements to determine what to do given some user input

217 |

The code below is an example:

218 |

219 | health = 100
220 | print "A vicious warg is chasing you."
221 | print "Options:"
222 | print "1 - Hide in the cave."
223 | print "2 - Climb a tree."
224 | input_value = raw_input("Enter choice:")
225 | if input_value == '1':
226 |     print 'You hide in a cave.'
227 |     print 'The warg finds you and injures your leg with its claws'
228 |     health = health - 10
229 | elif input_value == '2':
230 |     print 'You climb a tree.'
231 |     print 'The warg eventually looses interest and wanders off'
232 |                     
233 |
234 | 235 | 236 |
237 |

Iteration

238 |

It is often useful to perform a task and to repeat the process until a certain point is reached.

239 |

The repeated execution of a set of statements is called iteration

240 |

One way to acheive this, is with the while loop.

241 |

242 | x = 10
243 | while x > 0:
244 |     print x
245 |     x = x - 1
246 | print 'Done'
247 |                     
248 |

The while statement takes a predicate, and as long as it evaluates to True, the code block beneath it is repeated.

249 |

This creates a loop. Without the `x = x - 1` statement, this would be an infinite loop

250 |
251 | 252 |
253 |

While loops

254 |

Consider the following example that uses iteration to derive a factorial

255 |

(A factorial of a number is equal to that number * every positive integer less than that number. E.g. The factorial of 4 is 4 * 3 * 2 * 1, which equals 24

256 |

257 | input_value = raw_input('Enter a positive integer:')
258 | n = int(input_value)
259 | result = 1
260 | while n > 1:
261 |     result = result * n
262 |     n = n - 1
263 | print "The factorial of " + input_value + " is:"
264 | print result
265 |                     
266 |

N.B. - This implementation does not work for negative numbers. Why?

267 |
268 | 269 |
270 |

For loops

271 |

It is also useful to loop through a collection of elements, visiting each one to do some work, then stopping once all elements are processed.

272 |

This can be accomplished with a for loop

273 |

First, we need a collection. We create a list of numbers to loop over. This is called `numbers` in the following example

274 |

275 | numbers = [1, 3, 8]
276 | for number in numbers:
277 |     print "The current number is:"
278 |     print number
279 |                     
280 |
281 | 282 |
283 |

For loops continued

284 |

Let's examine the example carefully

285 |

286 | numbers = [1, 3, 8]
287 | for number in numbers:
288 |     print "The current number is:"
289 |     print number
290 |                     
291 |

The for loop has three parts:

292 |
    293 |
  • The collection to loop over - numbers
  • 294 |
  • The name to give each element when the loop begins again - number
  • 295 |
  • The block of statements to execute with the element - The two print statements
  • 296 |
297 |
298 | 299 | 300 |
301 |

Let's Develop It

302 |
    303 |
  • Write a program that obtains user input like the last program
  • 304 |
  • However, this program should not exit until the user types "quit".
  • 305 |
  • Hint: A loop should help you
  • 306 |
307 |
308 | 309 | 310 |
311 |

Functions

312 |

Also known as "procedures"

313 |

- A named unit of code that performs a specific task

314 |

When one uses a function, one makes a function call

315 |

We have already made a function call when using the type, int, or float functions

316 | 317 |

318 | a = '3'
319 | print type(a)
320 | a = float(a)
321 |                     
322 |
323 | 324 |
325 |

Function calls

326 |

327 | a = 3
328 | print type(a)
329 |                     
330 |

A function can take arguments

331 |

In the example above, the variable `a` is passed as an argument to the function `type`

332 |

Arguments can also be called parameters

333 |

334 | # Some more function call examples
335 | 
336 | int('32')
337 | str(32)
338 |                     
339 |
340 | 341 |
342 |

Function definition

343 |

The following example is a function definition. This allows us to create our own functions

344 |

345 | def print_plus_5(x):
346 |     print x + 5
347 |                     
348 |

The function definition has the following parts

349 |
    350 |
  • The def keyword signifies we are defining a function
  • 351 |
  • The name of the function being defined - `print_plus_5`
  • 352 |
  • The arguments in parentheses - `x`
  • 353 |
  • The function body, which is a block of indented code that executes when the function is called. - `print x + 5`
  • 354 |
355 |
356 | 357 |
358 |

Function returns

359 |

A function can also return a value

360 |

To do this, one uses the return keyword

361 |

362 | def plus_5(x):
363 |     return x + 5
364 | 
365 | y = plus_5(4)
366 |                     
367 |
    368 |
  • This allows us to call a function to obtain a value for later use. (Not the same as printing the value)
  • 369 |
  • In this example, the function call `plus_5(4)` evaluates to 9, and y is set to this value
  • 370 |
  • To determine what a function will return, use the substitution method.
  • 371 |
  • If return is not used, the function returns None
  • 372 |
373 |
374 | 375 |
376 |

Functions with no arguments

377 |

A function does not have to take arguments, as in the following example: 378 |


379 | def newline():
380 |     print ''
381 | 
382 | newline()
383 | # prints an empty line. Nothing is returned
384 |                     
385 |

This is useful when the function does some work but doesn't need any parameters. i.e. The function is intended to always do the same thing

386 |
387 | 388 |
389 |

Functions with more than one argument

390 |

A function can also take more than one argument separated by commas. For example:

391 |

392 | def find_rectangle_area(width, height):
393 |     return width * height
394 | 
395 | area = find_rectangle_area(3, 4)
396 | # area is set to the value 12
397 |                     
398 |
399 | 400 |
401 |

Scope

402 |

The scope of a variable is the area of code in which a variable is still valid and can be used.

403 |

Variables defined within a function can not be used elsewhere.

404 |

405 | def get_triangle_area(base, height):
406 |     rect_area = base * height
407 |     return rect_area / 2.0
408 | 
409 | triangle_area = get_triangle_area(10, 20)
410 | 
411 | print height
412 | # NameError
413 | print rect_area
414 | # NameError
415 |                     
416 |
417 | 418 |
419 |

Import statements

420 |

The import statement allows us to use Python code that is defined in one file in a different file, or inside of the shell.

421 |

The from keyword allows us to only import parts of a Python file

422 |

423 | # In knights.py
424 | def shrubbery():
425 |     print "I am a shrubber"
426 | 
427 | def ni():
428 |     print "Ni!" * 3
429 | 
430 | # Run a Python shell in the same directory as knights.py and enter the following
431 | import knights
432 | knights.shrubbery()
433 | knights.ni()
434 | 
435 | # or
436 | from knights import shrubbery, ni
437 | shrubbery()
438 | ni()
439 |                     
440 |
441 | 442 | 443 |
444 |

Let's Develop It

445 |
    446 |
  • Write a program that uses at least one function to solve a geometry problem
  • 447 |
  • Hint: You might use a loop that obtains user input, does the calculation, then prints the answer. As before, the user should be able to quit by entering "quit"
  • 448 |
  • Hint: You can import your function in the shell and call it with different parameters to test it out
  • 449 |
  • Hint: Download geometry.py and use it as an example
  • 450 |
451 |

If you'd like to try something different or in addition, try the next slide...

452 |
453 | 454 |
455 |

Let's Develop It

456 |
    457 |
  • Write a program that asks the user to guess a number between a given range, such as 1 to 10
  • 458 |
  • The program should give the user hints such as "too high" or "too low". Alternatively, the hints might be "warm" or "cold" depending on how close they are to the number
  • 459 |
  • The computer will need to have a random number for the user to guess:
  • 460 |
    
    461 | #At the top of the file
    462 | from random import randint
    463 | 
    464 | # Use this line where you need to have a random number.
    465 | # (Hint, this is probably used before the user input loop)
    466 | random_number = randint(1, 10)
    467 |                         
    468 |
469 |
470 | 471 |
472 |

Questions?

473 |
474 | 475 |
476 |
477 |
478 | 482 |
483 |
484 | 485 | 486 | 487 | 488 | 511 | 512 | 513 | 514 | -------------------------------------------------------------------------------- /set1/class4.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Intro to Python ~ Girl Develop It 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 |
33 | 34 |
35 | 36 |
37 | 38 |

Intro to Python

39 |

Class 4

40 |
41 | 42 |
43 |

Review

44 |
    45 |
  • Method calls
  • 46 |
  • Combining lists and dictionaries
  • 47 |
  • Builtins for collections
  • 48 |
49 |
50 | 51 | 52 |
53 |

Functions on Dictionaries

54 |

55 |

 56 | character = {
 57 |     'x': 10,
 58 |     'y': 20,
 59 |     'health': 100,
 60 | }
 61 | 
 62 | def injure(character, damage):
 63 |     character['health'] = character['health'] - damage
 64 |     if character['health'] < 0:
 65 |         character['health'] = 0
 66 | 
 67 | def heal(character, amount):
 68 |     character['health'] = character['health'] + amount
 69 |     if character['health'] > 100:
 70 |         character['health'] = 100
 71 |                     
72 |
73 | 74 |
75 |

Classes

76 |

A class creates a new type of object.

77 |

A class defines the attributes and methods of objects of that type

78 |

Classes are used to create new objects of that type

79 |

 80 | class Character():
 81 | 
 82 |     def __init__(self, x, y, health):
 83 |         self.x = x
 84 |         self.y = y
 85 |         self.health = health
 86 | 
 87 | character = Character(10, 20, 100)
 88 |                     
89 |
90 | 91 |
92 |

A Sense of Self

93 |

The first argument to every method is self.

94 |

self contains the attributes and methods for the current object

95 |

 96 | class Character():
 97 | 
 98 |     def __init__(self, x, y, health):
 99 |         self.x = x
100 |         self.y = y
101 |         self.health = health
102 | 
103 | character = Character(10, 20, 100)
104 |                     
105 |
106 | 107 |
108 |

The __init__ Method

109 |

This method defines what the class should do when creating a new object.

110 |

111 | class Character():
112 | 
113 |     def __init__(self, x, y, health):
114 |         self.x = x
115 |         self.y = y
116 |         self.health = health
117 | 
118 | character_a = Character(10, 20, 100)
119 | character_b = Character(10, 20, 100)
120 |                     
121 |

To create a new Character, the syntax looks like a function call. These arguments are passed to the __init__ method

122 |
123 | 124 |
125 |

Class Methods

126 |

A class also defines methods, which are functions that operate on objects of that type

127 |

Assigning values to an attribute on self is how we mutate the object's state.

128 |

129 | # inside the character class
130 | 
131 |     def heal(self, amount):
132 |         self.health = self.health + amount
133 |         if self.health > 100:
134 |             self.health = 100
135 | 
136 |     def injure(self, amount):
137 |         self.health = self.health - amount
138 |         if self.health < 0:
139 |            self.health = 0
140 | 
141 | character = Character(10, 20, 100)
142 | character.injure(10)
143 |                     
144 |
145 | 146 | 147 |
148 |

Let's Develop It

149 |
    150 |
  • In your text editor, create your own class with an __init__ method, and at least one other method.
  • 151 |
  • Open a Python shell and import the class. Create one or more objects from the class
  • 152 |
  • If time allows, create a function that creates objects from your class, calls a method, and prints one of its attributes
  • 153 |
  • Use the next slide as an example
  • 154 |
155 |
156 | 157 |
158 |

159 | # in character.py
160 | class Character():
161 | 
162 |     def __init__(self, x, y, health):
163 |         self.x = x
164 |         self.y = y
165 |         self.health = health
166 | 
167 |     def heal(self, amount):
168 |         self.health = self.health + amount
169 |         if self.health > 100:
170 |             self.health = 100
171 |                     
172 |

173 | # in Python shell
174 | from character import Character
175 | character_a = Character(10, 20, 100)
176 | character_a.injure(10)
177 | print "character health is: " + character_a.health
178 |                     
179 |
180 | 181 | 182 | 183 |
184 |

Inheritance

185 |

A class can inherit from another class.

186 |

A class that inherits from another is called the "child class" and obtains the methods and attributes of its "parent"

187 |

188 | class Mobile(object):
189 |     """
190 |     An object with an x, y position, and methods for moving
191 |     """
192 | 
193 |     def __init__(self, x, y):
194 |         self.x = x
195 |         self.y = y
196 | 
197 |     def move_up():
198 |         self.y = self.y - 1
199 | 
200 |     # ... methods for move_down, move_left, and move_right
201 |                     
202 |
203 | 204 |
205 |

Inheritance Continued

206 |

The move_up method is overridden in the child class below:

207 |

208 | class BoundedMobile(Mobile):
209 |     """
210 |     An object with an x, y position, and methods for moving
211 |     The x, y position must be within bounds
212 |     """
213 | 
214 |     def move_up():
215 |         self.y = self.y - 1
216 |         if self.y < 0:
217 |             self.y = 0
218 |                     
219 |

See mobile.py for a more complete example.

220 |
221 | 222 |
223 |

What's Super about Super

224 |

super is often helpful when writing methods that override the method of the parent class

225 |

226 | class BoundedMobile(Mobile):
227 |     """
228 |     An object with an x, y position, and methods for moving
229 |     The x, y position must be within bounds
230 |     """
231 | 
232 |     def move_up():
233 |         super(BoundedMobile, self).move_up()
234 |         if self.y < 0:
235 |             self.y = 0
236 |                     
237 |

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

238 |
239 | 240 |
241 |

Composition

242 |

Classes can also use the technique of composition

243 |

This simply means that a given object contains other objects within it.

244 |

This often leads to a clearer and simpler design

245 |

246 | class Grid(object):
247 | 
248 |     def __init__(self, x_limit, y_limit):
249 |         self.x_limit = x_limit
250 |         self.y_limit = y_limit
251 |         self.mobiles = []
252 | 
253 |     def add_mobile(self, x, y):
254 |         mob = BoundedMobile(x, y, self.x_limit, self.y_limit)
255 |         mobs = self.mobiles.get((x, y), [])
256 |         mobs.append(mob)
257 |         self.mobiles[(x, y)] = mobs
258 |                     
259 |
260 | 261 |
262 |

Composition Continued

263 |

Given the class on the previous slide, the following code creates mobiles within the grid object. (Complete code is available in the aforementioned mobile.py file.)

264 |

265 | from mobile import Grid
266 | 
267 | grid = Grid(7, 7)
268 | grid.add_mobile(1, 2)
269 | grid.add_mobile(0, 1)
270 | grid.add_mobile(0, 1)
271 | 
272 | grid.display_grid()
273 |                     
274 |
275 | 276 | 277 |
278 |

Let's Develop It

279 |

Create a class that uses inheritance, composition, or both.

280 |

To help you, use your work from the last exercise or the classes from mobile.py

281 |
282 | 283 | 284 |
285 |

List Comprehensions

286 |

I have a list and I have something I want to do to each element to create a new list

287 |

288 | squares = []
289 | for number in range(11):
290 |     squares.append(number ** 2)
291 |                     
292 |

This pattern is so common, there is a shorter way to express it:

293 |

294 | squares = [number ** 2 for number in range(11)]
295 |                     
296 |

This is called a list comprehension

297 |
298 | 299 |
300 |

Generators

301 |

A generator is like a list, but it is evaluated when it is used rather than when it is defined.

302 |

Generators are useful when the list may be very large or when the task is time consuming

303 |

304 | #Define a generator
305 | def find_squares(numbers):
306 |     for number in numbers
307 |         yield number ** 2
308 | 
309 | #Iterate on a generator like a list
310 | for square in find_squares(range(10)):
311 |     print square
312 |                     
313 |

A function with a yield statement creates a generator. Each yield statement "yields" the next value in the sequence

314 |
315 | 316 |
317 |

Generator Comprehensions

318 |

A generator comprehension is created the same way as list comprehension, but replacing the square brackets with parenthesis.

319 |

320 | ten_squares = (number ** 2 for number in range(10))
321 |                     
322 |

These are used liberally in the functions of books.py example from class 3.

323 |
324 | 325 |
326 |

Higher order functions

327 |

A higher order function is a function that returns a function, takes a function as an argument, or both

328 |

One commonly used higher order function that is a Python builtin is called map

329 |

330 | # Define any function
331 | def sqaure(number):
332 |     return number ** 2
333 | 
334 | # Pass the function to map along with an iterable
335 | squares = map(square, range(10))
336 |                     
337 |

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.

338 | 339 | 340 |
341 |

Let's Develop It

342 |

Choose among any of these projects (Resources available on the next page):

343 |
    344 |
  • Search the Web - Write a program that searches the web using DuckDuckGo and displays results. 345 |
  • 346 |
  • Encryption - Write a program that encrypts a string from user input, or file and is able to decrypt it as well. 347 |
  • 348 |
  • Command Line Game - Create a simple game that runs inside the terminal. 349 |
  • 350 |
351 | 352 |
353 |

Let's Develop It Resources

354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 |
Search the Webpython-duckduckgo 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.)
EncryptionRead about the Caesar Cipher or find a similarly simple encryption mechanism online. You should find the ord() and chr() functions helpful, as well as the modulus operator '%'
364 |

continued on next page...

365 |
366 | 367 |
368 |

Let's Develop It Resources Continued

369 | 370 | 371 | 372 | 373 | 374 |
Command Line GameThis 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 Colossal Cave Adventure and Zork
375 |
376 | 377 |
378 |

Future Resources

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 |
Python.org DocumentationOfficial Python Documentation
Think PythonOnline and print book with exercises.
Learn Python the Hard WayOnline and print book with exercises
Google's Python ClassVideo lectures coupled with exercises
New CoderIdeas for slightly larger projects and resources to get you started. Projects include accessing API's, scraping pages, writing IRC bots, and others.
Girl Develop ItLocal workshops, events, and coding sessions
406 |
407 | 408 |
409 |

Questions?

410 |
411 | 412 |
413 |
414 | 418 |
419 |
420 | 421 | 422 | 423 | 424 | 447 | 448 | 449 | 450 | -------------------------------------------------------------------------------- /set1/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Intro to Python ~ Girl Develop It 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | 32 |
33 | 34 |
35 | 36 |
37 | 38 |

Intro to Python

39 | Class 1 40 | Class 2 41 | Class 3 42 | Class 4 43 |
44 |
45 |
46 | 50 |
51 |
52 | 53 | 54 | 55 | 56 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /set2/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Intro to Python ~ Girl Develop It 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 |
28 | 29 |
33 |
34 |
35 |
36 | 40 |
41 |
42 | 43 | 44 | 45 | 46 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /set2/slides/contents.md: -------------------------------------------------------------------------------- 1 | ####[Part 1](?part=part1) - Intro to programming in Python 2 | 3 | What is programming? What is Python? We'll tackle these concepts, set up a development environment, and get started working in the Python shell. 4 | @@@ 5 | 6 | ####[Part 2](?part=part2) - Structured programming: Functions, Loops, and conditionals 7 | 8 | We'll be creating small programs in the text editor, implementing control flow and loading these programs into the shell. 9 | @@@ 10 | 11 | ####[Part 3](?part=part3) - Python data structures and other essential built-ins 12 | 13 | Lists, dictionaries and other built-in containers give the Python programmer tremendous power. We'll use these combined with other Python built-ins to process text files for information. 14 | @@@ 15 | 16 | ####[Part 4](?part=part4) - Object oriented programming 17 | 18 | What is Object-Oriented Programming and how can it help make programming easier? We'll also get started on some projects that you can do with your new Python skills. 19 | @@@ 20 | 21 | ####[Exercises](?part=exercises) - Additional Exercises 22 | -------------------------------------------------------------------------------- /set2/slides/exercises.md: -------------------------------------------------------------------------------- 1 | ![Girl Develop It Logo](../images/gdi_logo_badge.png) 2 | 3 | ###Intro to Python 4 | ####Additional Exercises 5 | @@@ 6 | 7 | ###Functions 8 | 9 | * Write a program that uses at least one function to solve a geometry problem 10 | 11 | * The program will generally have three steps: 12 | 13 | * Obtain input 14 | * Call a function to calculate the answer 15 | * Display the answer 16 | 17 | * Hint: You can take user input with raw_input() as before, or use the example 18 | below to take arguments from the command line 19 | * Download [geometry.py](http://calebsmith.github.io/gdi-intro-python/examples/geometry.py) and use it as an example 20 | 21 | Note: Let's Develop It 15 Minutes 22 | 23 | @@@ 24 | 25 | ###Text processing 26 | 27 | Write a program that opens a text file and does some processing. 28 | 29 | * The program should take a word as input and determine if the word appears in the file 30 | 31 | * 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 32 | 33 | The next page lists the things you will need. 34 | 35 | Note: Let's develop it: 15 minutes 36 | 37 | @@@ 38 | 39 | ###Text processing - Requirements 40 | 41 | * Use the functions from [helpers.py](http://calebsmith.github.io/gdi-intro-python/examples/helpers.py) to help with reading in the lines and/or words of the file 42 | 43 | * Download a plain text english dictionary like the following: [english.txt](http://calebsmith.github.io/gdi-intro-python/examples/english.txt) and put it into the same directory as your python file. 44 | 45 | * Download a book in plain text from [Project Gutenburg](http://www.gutenberg.org/wiki/Main_Page) and put it into the same directory as your python file. 46 | 47 | The next slide shows some code to help you get started. 48 | 49 | @@@ 50 | 51 | ###Text processing - Example Code 52 | 53 | ```python 54 | from helpers import generate_cleaned_lines 55 | 56 | def is_word_in_file(word, filename): 57 | for line in generate_cleaned_lines(filename): 58 | # line will be a string of each line of the file in order 59 | # Your code goes here. 60 | # Your code should do something with the word and line variables and assign the value to a variable for returning 61 | input_word = raw_input("Enter a word to search for:") 62 | answer = is_word_in_file(input_word, 'pride.txt') 63 | # Display the answer in some meaningful way 64 | ``` 65 | 66 | I have used [Pride and Prejudice](http://calebsmith.github.io/gdi-intro-python/examples/pride.txt) 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 67 | -------------------------------------------------------------------------------- /set2/slides/menu.md: -------------------------------------------------------------------------------- 1 | Girl Develop It Logo 2 | 3 | ###Intro to Python 4 | ####Menu 5 | 6 | [Section 1](?part=part1) 7 | [Section 2](?part=part2) 8 | [Section 3](?part=part3) 9 | [Section 4](?part=part4) 10 |
11 | [Additional Exercises](?part=exercises) 12 | [Contents](?part=contents) 13 | -------------------------------------------------------------------------------- /set2/slides/part1.md: -------------------------------------------------------------------------------- 1 | ![Girl Develop It Logo](../images/gdi_logo_badge.png) 2 | 3 | ###Intro to Python 4 | ####Section 1 5 | @@@ 6 | 7 | ## Welcome 8 | Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction. 9 | 10 | Some rules 11 | 12 | * We are here for you 13 | * Every question is important 14 | * Help each other 15 | * Have fun 16 | @@@ 17 | 18 | ###What we will cover today 19 | 20 | * Why Python? 21 | * What is programming? 22 | * Variables and arithmetic 23 | * Statements and Error Messages 24 | * Development Environment Setup 25 | @@@ 26 | 27 | ###Why Python? 28 | 29 | * Suitable for beginners, yet used by professionals 30 | * Readable, maintainable code 31 | * Rapid rate of development 32 | * Few "magical" side-effects 33 | * Variety of applications 34 | Note: Block 1 begins - 25 minutes 35 | @@@ 36 | 37 | ###What is Python used for? 38 | 39 | * System Administration (Fabric, Salt, Ansible) 40 | * 3D animation and image editing (Maya, Blender, Gimp) 41 | * Scientific computing (numpy, scipy) 42 | * Web development (Django, Flask) 43 | * Game Development (Civilization 4, EVE Online) 44 | @@@ 45 | 46 | ###Who is using Python? 47 | 48 | * Disney 49 | * Dropbox 50 | * Canonical and Red Hat 51 | * Google 52 | * NASA 53 | Note: Caktus uses Python 54 | @@@ 55 | 56 | ###What is programming? 57 | 58 | * Teaching the computer to do a task 59 | * A program is made of one or more files of code, each of which solve part of the overall task 60 | * Programming code is human readable but also needs a form that the computer can run directly. This form is not human readable. 61 | * To create the form of code the computer can use, we use the Python interpreter. Other languages use other interpreters or a compiler 62 | * Don't focus on what's "under the hood" for now. We will "drive the car" first 63 | * In other words, there are many layers to the onion. We start at one layer and slowly move toward layers that are beneath or above us 64 | @@@ 65 | 66 | ###Command line, Python Shell, Text Editors 67 | 68 | Program | Description 69 | -------------|---------- 70 | Terminal | A program that has a command line interface and issues commands to the operating system. 71 | Python Shell | A command line program that runs inside of the terminal, takes Python code as input, interprets it, and prints out any results. 72 | Text Editor | A program that opens text files and allows the user to edit and save them. (Different than a word processor). 73 | @@@ 74 | 75 | ###Example Text Editors 76 | 77 | Platform | Examples 78 | ----------|---------- 79 | Linux | Gedit, Jedit, Kate 80 | MacOSX | TextMate, TextWrangler 81 | Windows | Notepad++ 82 | All | Sublime Text, Vim, Emacs 83 | @@@ 84 | 85 | ###Let's Develop It 86 | Let's setup our computer for Python programming 87 | 88 | * Let's install a text editor - [Install Sublime Text 3](http://www.sublimetext.com/3) 89 | * [Install Python](http://www.python.org/download/) - (This step is for Windows users only. GNU/Linux and MacOSX come with Python installed) 90 | * (Windows only): After installing Python, open the "powershell" program and type: 91 |
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
92 | * Locate and run the terminal program. Type 'python' and hit enter. 93 | * More setup instructions are available: [here](http://learnpythonthehardway.org/book/ex0.html) 94 | * (You can, but don't have to install the other text editors recommended in this guide) 95 | Note: 15 minutes 96 | @@@ 97 | 98 | ##Block 2 99 | Note: 30 minutes 100 | @@@ 101 | 102 | ###Working in the Python Shell 103 | 104 | Open up your terminal and type 'python' 105 | 106 | * Follow along with the examples in the slides. Type them in! 107 | * Feel free to explore as well. You will not accidentally break things 108 | * $ means you are in the terminal (not python). >>> means you are in python 109 | * Type exit() to leave python and return to the terminal. 110 | 111 | @@@ 112 | 113 | ###Variables and Arithmetic 114 | ```python 115 | >>> 3 + 4 116 | 7 117 | >>> 2 * 4 118 | 8 119 | >>> 6 - 2 120 | 4 121 | >>> 4 / 2 122 | 2 123 | ``` 124 | ```python 125 | >>> a = 2 126 | >>> print a 127 | 2 128 | >>> b = 3 129 | >>> c = a + b 130 | >>> print c 131 | 5 132 | ``` 133 | ```python 134 | >>> a = 0 135 | >>> a = a + .5 136 | >>> print a 137 | 0.5 138 | ``` 139 | @@@ 140 | 141 | ###Strings 142 | ```python 143 | >>> a = 'Hello ' 144 | >>> b = 'World' 145 | >>> c = a + b 146 | >>> print c 147 | 'Hello World' 148 | ``` 149 | ```python 150 | >>> a = "Spam " 151 | >>> b = a * 4 152 | >>> print b 153 | "Spam Spam Spam Spam" 154 | ``` 155 | @@@ 156 | 157 | ###Data types 158 | * Variables are names of objects 159 | * Among other things, variables are used to represent something that can't be known until the program is run 160 | * Objects always have a "type" 161 | * The type of an object helps define what it can do 162 | * The type can be found using: type() 163 | * type() is a function. We call it by using parenthesis and pass it an object by placing the object inside the parenthesis 164 | ```python 165 | >>> print type(4) 166 | 167 | >>> a = 4 168 | >>> print type(a) 169 | 170 | >>> print type("But I don't like spam") 171 | 172 | >>> print type(3.5) 173 | 174 | ``` 175 | @@@ 176 | 177 | ###Data types - continued ... 178 | * Objects can be used with a set of operators 179 | * An int or float can be used with any of: +, -, *, / 180 | * A string can be used with any of: +, * 181 | * What happens if we try to use division or subtraction with a string? 182 | ```python 183 | >>> print "Spam" / "eggs" 184 | Traceback (most recent call last): 185 | File "", line 1, in 186 | TypeError: unsupported operand type(s) for /: 'str' and 'str' 187 | ``` 188 | @@@ 189 | 190 | 191 | ###Errors 192 | 193 | * There are different kinds of errors that can occur. We've seen a few of these so far 194 | * A runtime error results in an Exception. An Exception gives us some information about the nature of the error and how to correct it 195 | * One type of exception is a SyntaxError. This results when our code can not be evaluated because it is incorrect at a syntactic level. In other words, we are not following the "rules" of the language. 196 | * Some other examples are the TypeError and NameError exceptions. 197 | @@@ 198 | 199 | ###Errors - continued ... 200 | 201 | * A \# is a code comment. These are not evaluated by Python 202 | 203 | ```python 204 | # SyntaxError - Doesn't conform to the rules of Python. 205 | # This statement isn't meaningful to the computer 206 | >>> 4spam)eggs(garbage) + 10 207 | 208 | # NameError - Using a name that hasn't been defined yet. 209 | >>> a = 5 210 | >>> print b 211 | 212 | # TypeError - Using an object in a way that its type does not support 213 | >>> 'string1' / 'string2' 214 | ``` 215 | @@@ 216 | 217 | ###Let's Develop It 218 | * We'll practice what we've learned in the shell 219 | * Review the slides on your computer and practice entering any commands you didn't fully understand before 220 | * Ask the teacher or a TA for any help 221 | Note: Let's develop it: 30 minutes. 222 | @@@ 223 | 224 | ###Using the terminal 225 | Try each of the following commands in turn: 226 | 227 | Command | Short for | Description 228 | ----------------|-------------------------|------------- 229 | pwd | Print working directory | Displays what folder you are in 230 | ls | List | Displays the files and folders in the current folder 231 | cd | Change Directory | Change to another folder, where is the target 232 | cat | Concatenate k | Prints the contents of the file 233 | file | File | Displays the type of the file 234 | 235 | Note: Block 3 begins, 30 minutes 236 | @@@ 237 | 238 | ###Creating a folder 239 | We need a folder to save and run our code from. 240 | 241 | ($ shows the shell prompt where commands are entered. Lines without $ are output) 242 | ```bash 243 | $ cd 244 | $ pwd 245 | /home/username ( or /User/username or similar) 246 | $ mkdir gdipython 247 | $ cd gdipython 248 | $ pwd 249 | /home/username/gdipython 250 | ``` 251 | Now that the folders are made, we only have to use this in the future: 252 | 253 | `$ cd ~/gdipython` 254 | @@@ 255 | 256 | ###The Text Editor 257 | Open sublime text. 258 | 259 | * Click File, then Open folder. Navigate to the gdipython folder we created and click "open" 260 | * In the text editor, enter the following: 261 | 262 | ```python 263 | print 'This is a Python program' 264 | ``` 265 | 266 | * Click file, save as. Type 'program.py' and click ok. 267 | 268 | --- 269 | Open a terminal and type 270 | ```bash 271 | $ cd 272 | $ cd gdipython 273 | $ python program.py 274 | ``` 275 | 276 | You should see the terminal print: 277 | 278 | `This is a Python program` 279 | @@@ 280 | 281 | ###User Input 282 | To obtain user input, use 'raw_input()'. This will become a string 283 | 284 | We use float() to make it a number 285 | 286 | Change the program.py text to the following and run it again 287 | ```python 288 | input_value = raw_input("Enter a radius:") 289 | radius = float(input_value) 290 | area = 3.14159 * radius * radius 291 | print "The area of a circle with radius", input_value, "is", area 292 | ``` 293 | @@@ 294 | 295 | ###Let's Develop It 296 | Write your own program that uses raw_input and does something else with the value 297 | 298 | You can use float() or int() to treat the input as a number if you need a number, or you can use the input directly if you need a string 299 | 300 | Note: Let's develop it: 15 minutes 301 | @@@ 302 | 303 | ###Questions? 304 | -------------------------------------------------------------------------------- /set2/slides/part2.md: -------------------------------------------------------------------------------- 1 | ![Girl Develop It Logo](../images/gdi_logo_badge.png) 2 | 3 | ###Intro to Python 4 | ####Section 2 5 | @@@ 6 | 7 | ###Review 8 | 9 | * Arithmetic 10 | * Variables 11 | * Data types 12 | * Text editor, command line, and python shell 13 | @@@ 14 | 15 | 16 | ###What we will cover today 17 | * Boolean Expressions and Conditionals 18 | * Loops 19 | * Functions 20 | @@@ 21 | 22 | ###Boolean Expressions 23 | We can tell the computer to compare values and return True or False. These are called *Boolean expressions* 24 | 25 | * Test for equality by using ==. (This is not the same as using =) 26 | * Test for greater than and less than using > and < 27 | ```python 28 | >>> a = 5 29 | >>> b = 5 30 | >>> print a == b 31 | True 32 | >>> print a < 3 33 | False 34 | >>> # Combine comparison and assignment 35 | >>> c = a == b 36 | >>> print c 37 | True 38 | ``` 39 | 40 | Note: Block 1 - 25 Minutes 41 | @@@ 42 | 43 | ###Boolean Expressions continued 44 | 45 | The following chart shows the various Boolean operators 46 | 47 | Expression | Tests 48 | -----------|----------------- 49 | a == b | a is equal to b 50 | a != b | a does not equal b 51 | a < b | a is less than b 52 | a > b | a is greater than b 53 | a <= b | a is less than or equal to b 54 | a >= b | a is greater than or equal to b 55 | 56 | ```python 57 | >>> a = 3 58 | >>> b = 4 59 | >>> print a != b 60 | True 61 | >>> print a <= 3 62 | True 63 | >>> print a >= 4 64 | False 65 | ``` 66 | @@@ 67 | 68 | ###Conditionals 69 | 70 | When we want different code to execute dependending on certain criteria, we use a **conditional** 71 | We achieve this using **if** statements 72 | ```python 73 | if x == 5: 74 | print 'x is equal to 5' 75 | ``` 76 | We often want a different block to execute if the statement is false. This can be accomplished using **else* 77 | ```python 78 | if x == 5: 79 | print 'x is equal to 5' 80 | else: 81 | print 'x is not equal to 5' 82 | ``` 83 | @@@ 84 | 85 | ###Indentation 86 | 87 | In Python, **blocks** begin when text is indented and ends when it returns to the previous indentation level. 88 | 89 | The line that begins a new block ends with a colon. 90 | 91 | Let's look at the previous example again with a few minor changes and examine the meaning of its indentation

92 | 93 | ```python 94 | if x == 5: 95 | print 'x is equal to 5' 96 | a = 1 97 | print 'Still in the x == 5 block' 98 | else: 99 | print 'x is not equal to 5' 100 | a = 2 101 | print 'Outside of the if or else blocks. This will run regardless of the value of x' 102 | print "Value of a is", a 103 | ``` 104 | @@@ 105 | 106 | ###Chained conditionals 107 | Conditionals can also be **chained** 108 | 109 | Chained conditionals use **elif** as an additonal check after the preceeding `if` predicate was False. 110 | ```python 111 | if x > 5: 112 | print 'x is greater than 5' 113 | elif x < 5: 114 | print 'x is less than 5' 115 | else: 116 | print 'x is equal to 5' 117 | ``` 118 | @@@ 119 | 120 | ###Nested conditionals 121 | Conditionals can also be **nested** 122 | 123 | Nested conditionals occur inside of other conditionals and are indented yet again. When each code block is complete, it is unindented 124 | ```python 125 | if x > 5: 126 | print 'x is greater than 5' 127 | if x > 10: 128 | print '...it is also greater than 10' 129 | print 'Done evaluating the x > 10 block' 130 | print 'Done evaluating the x > 5 block' 131 | ``` 132 | @@@ 133 | 134 | ###Let's Develop It 135 | Write a program that uses if statements to determine what to do given some user input 136 | 137 | The code below is an example: 138 | ```python 139 | health = 100 140 | print "A vicious warg is chasing you." 141 | print "Options:" 142 | print "1 - Hide in the cave." 143 | print "2 - Climb a tree." 144 | input_value = raw_input("Enter choice:") 145 | if input_value == '1': 146 | print 'You hide in a cave.' 147 | print 'The warg finds you and injures your leg with its claws' 148 | health = health - 10 149 | elif input_value == '2': 150 | print 'You climb a tree.' 151 | print 'The warg eventually looses interest and wanders off' 152 | print "Game under construction. Come back later" 153 | ``` 154 | Note: Let's develop it: 15 minutes 155 | @@@ 156 | 157 | ###Iteration 158 | It is often useful to perform a task and to repeat the process until a certain point is reached. 159 | 160 | The repeated execution of a set of statements is called **iteration** 161 | 162 | One way to acheive this, is with the **while** loop. 163 | ```python 164 | x = 10 165 | while x > 0: 166 | print x 167 | x = x - 1 168 | print 'Done' 169 | ``` 170 | The while statement takes a boolean expression, and as long as it evaluates to True, the code block beneath it is repeated. 171 | 172 | This creates a **loop**. Without the `x = x - 1` statement, this would be an **infinite loop** 173 | 174 | Note: Block 2 - 25 minutes 175 | @@@ 176 | 177 | ###While loops continued 178 | 179 | A loop can also terminate at any point with a **break** statement 180 | 181 | An infinite loop can be created using an expression that is always True. 182 | 183 | This is most commonly done with the constant True. 184 | 185 | ```python 186 | while True: 187 | name = raw_input("What is your name (type 'quit' to quit)? ") 188 | if name == 'quit': 189 | break 190 | print "Hello,", name 191 | ``` 192 | @@@ 193 | 194 | ###While loops example 195 | Consider the following example that uses iteration to derive a factorial 196 | 197 | (A factorial of a number is equal to that number * every positive integer less than that number. E.g. The factorial of 4 is `4 * 3 * 2 * 1`, which equals 24 198 | ```python 199 | input_value = raw_input('Enter a positive integer:') 200 | n = int(input_value) 201 | result = 1 202 | while n > 1: 203 | result = result * n 204 | n = n - 1 205 | print "The factorial of " + input_value + " is:" 206 | print result 207 | ``` 208 | N.B. - This implementation does not work for negative numbers. Why? 209 | @@@ 210 | 211 | ###For loops 212 | It is also useful to loop through a collection of elements, visiting each one to do some work, then stopping once all elements are processed. 213 | 214 | This can be accomplished with a **for** loop 215 | 216 | First, we need a collection. We create a **list** of numbers to loop over. This is called `numbers` in the following example 217 | ```python 218 | numbers = [1, 3, 8] 219 | for number in numbers: 220 | print "The current number is:" 221 | print number 222 | ``` 223 | @@@ 224 | 225 | ###For loops continued 226 | Let's examine the example carefully 227 | ```python 228 | numbers = [1, 3, 8] 229 | for number in numbers: 230 | print "The current number is:" 231 | print number 232 | ``` 233 | The for loop has three parts: 234 | 235 | * The collection to loop over - numbers 236 | * The name to give each element when the loop begins again - number 237 | * The block of statements to execute with the element - The two print statements 238 | @@@ 239 | 240 | ###Let's Develop It 241 | * Write a program that takes numbers from user input and adds thems all 242 | together for a final result. 243 | * This program should stop taking input, display the answer and exit when the user types "quit". 244 | * Hint: 245 | ```python 246 | result = 0 247 | while True: 248 | input_value = raw_input("Enter a number:") 249 | ... (put more code here) ... 250 | print "The final sum is", result 251 | ``` 252 | 253 | Note: Let's Develop It - 15 minutes 254 | @@@ 255 | 256 | 257 | ###Functions 258 | 259 | Also known as "procedures" 260 | 261 | - A named unit of code that performs a specific task 262 | 263 | When one uses a function, one makes a function **call** 264 | 265 | We have already made a function call when using the type, int, or float functions 266 | 267 | ```python 268 | >>> a = '3' 269 | >>> print type(a) 270 | 271 | >>> a = float(a) 272 | >>> print type(a) 273 | 274 | ``` 275 | 276 | Note: Block 3 - 40 Minutes 277 | @@@ 278 | 279 | ###Function calls 280 | 281 | ```python 282 | # Repeating the previous example for reference 283 | >>> a = 3 284 | >>> print type(a) 285 | 286 | ``` 287 | 288 | A function can take **arguments** (sometimes called **parameters**) 289 | 290 | In the example above, the variable `a` is passed as an argument to the function `type` 291 | 292 | A function call can be an argument to another function call. 293 | 294 | ```python 295 | # Some more function call examples 296 | 297 | >>> str(int(3.2)) 298 | '3' 299 | ``` 300 | @@@ 301 | 302 | ###Function definition 303 | 304 | The following example is a **function definition**. This allows us to create our own functions 305 | 306 | ```python 307 | def print_greeting(name): 308 | print "Hi", name 309 | print "How are you" 310 | ``` 311 | 312 | The function definition has the following parts 313 | 314 | * The def keyword signifies we are defining a function 315 | * The name of the function being defined - `print_greeting` 316 | * The arguments in parentheses - `name` 317 | * The function body, which is a block of indented code that executes when the function is called. - `print "Hi", name...` 318 | @@@ 319 | 320 | ###Function returns 321 | 322 | A function can also **return** a value 323 | 324 | To do this, one uses the **return** keyword 325 | ``` 326 | def plus_5(x): 327 | return x + 5 328 | 329 | y = plus_5(4) 330 | ``` 331 | 332 | * This allows us to call a function to obtain a value for later use. (Not the same as printing the value) 333 | * In this example, the function call `plus_5(4)` evaluates to 9, and y is set to this value 334 | * To determine what a function will return, use the substitution method. 335 | * If return is not used, the function returns None 336 | @@@ 337 | 338 | ###Functions with no arguments 339 | 340 | A function does not have to take arguments, as in the following example: 341 | 342 | ```python 343 | def newline(): 344 | print '' 345 | 346 | newline() 347 | # prints an empty line. Nothing is returned 348 | ``` 349 | 350 | This is useful when the function does some work but doesn't need any parameters. i.e. The function is intended to always do the same thing 351 | @@@ 352 | 353 | ###Functions with more than one argument 354 | 355 | A function can also take more than one argument separated by commas. For example: 356 | 357 | ```python 358 | def get_birthday_greeting(name, age): 359 | return "Happy birthday to " + name + " who just turned " + str(age) + "!" 360 | 361 | greeting = get_birthday_greeting("Virginia", 16) 362 | print greeting 363 | # Happy birthday to Virginia who just turned 16! 364 | ``` 365 | @@@ 366 | 367 | ###Scope 368 | 369 | The **scope** of a variable is the area of code in which a variable is still valid and can be used. 370 | 371 | Variables defined within a function can not be used elsewhere. 372 | 373 | ```python 374 | def get_average(a, b): 375 | total = a + b 376 | return total / 2.0 377 | 378 | avg = get_average(10, 20) 379 | 380 | print avg 381 | # 15 382 | print a 383 | # NameError 384 | print total 385 | # NameError 386 | ``` 387 | 388 | Note: Draw a diagram with bubbles 389 | @@@ 390 | 391 | ###Import statements 392 | 393 | The **import** statement allows us to use Python code that is defined in one file in a different file, or inside of the shell. 394 | 395 | The **from** keyword allows us to only import parts of a Python file 396 | 397 | ```python 398 | # In knights.py 399 | def shrubbery(): 400 | print "I am a shrubber" 401 | 402 | def ni(number): 403 | print "Ni!" * 3 404 | ``` 405 | 406 | ```python 407 | # Run a Python shell in the same directory as knights.py and enter the following 408 | import knights 409 | 410 | knights.shrubbery() 411 | knights.ni() 412 | 413 | # or 414 | from knights import shrubbery, ni 415 | shrubbery() 416 | ni() 417 | ``` 418 | @@@ 419 | 420 | 421 | ###Let's Develop It 422 | * Write a game that displays a board and allows a player to move on the board. 423 | 424 | * The beginning of this program has been started and is available here as 425 | [game1.py](http://calebsmith.github.io/gdi-intro-python/examples/game1.py) 426 | 427 | * More instructions can be found in the game1.py file 428 | 429 | * You'll also need to download the board.dat file to the same folder. 430 | [board.dat](http://calebsmith.github.io/gdi-intro-python/examples/board.dat) 431 | 432 | * If you are stuck ask the teacher or a TA for help. 433 | 434 | Note: Let's Develop It 25 minutes 435 | @@@ 436 | 437 | 438 | ###Let's Develop It 439 | * Improve our adventure game by preventing the player from walking through 440 | walls 441 | 442 | * The beginning of this program has been started and is available here as 443 | [game2.py](http://calebsmith.github.io/gdi-intro-python/examples/game2.py) 444 | 445 | * You'll also need to download the board.dat file to the same folder. 446 | [board.dat](http://calebsmith.github.io/gdi-intro-python/examples/board.dat) 447 | 448 | * If you are stuck ask the teacher or a TA for help. 449 | 450 | * If you finish early, consider adding a feature of your own or helping your 451 | neighbor 452 | 453 | Note: Let's Develop It 30 minutes 454 | @@@ 455 | 456 | ###Questions? 457 | -------------------------------------------------------------------------------- /set2/slides/part3.md: -------------------------------------------------------------------------------- 1 | ![Girl Develop It Logo](../images/gdi_logo_badge.png) 2 | 3 | ###Intro to Python 4 | ####Section 3 5 | @@@ 6 | 7 | ###Review 8 | 9 | * Conditionals - if, elif, else 10 | * Loops - while, for 11 | * Functions - calls, definitions, arguments, return 12 | 13 | Note: Block 1 - 25 Minutes 14 | @@@ 15 | 16 | 17 | ###What we will cover today 18 | 19 | * More functions 20 | * Method calls 21 | * Lists and dictionaries 22 | * Python built-in funtions 23 | 24 | @@@ 25 | 26 | ###More with Functions 27 | Functions can also call other functions 28 | 29 | One can use this to break up tasks into small piece that rely on others to do their work 30 | 31 | ```python 32 | def get_tip(bill_amount): 33 | return bill_amount * 0.20 # 20% tip for good service 34 | 35 | def get_tax(subtotal): 36 | return subtotal * 0.0675 # 6.75% in Orange County, NC 37 | 38 | def print_receipt(subtotal): 39 | tax = get_tax(subtotal) 40 | bill_amount = subtotal + tax 41 | tip = get_tip(bill_amount) 42 | total = bill_amount + tip 43 | 44 | print "Subtotal: $" + str(subtotal) 45 | print "Tax at " + str(orange_county_tax_rate * 100) + "%: $" + str(tax) 46 | print "Tip at " + str(tip_for_good_service * 100) + "%: $" + str(tip) 47 | print "Grand Total: $" + str(total) 48 | ``` 49 | 50 | @@@ 51 | 52 | ###Function Composition 53 | **Function composition** is when the output of one funtion serves as the input of another 54 | 55 | ```python 56 | def increase(x): 57 | return x + 1 58 | 59 | def decrease(x): 60 | return x - 1 61 | 62 | def double(x): 63 | return 2 * x 64 | 65 | print double(increase(5)) 66 | # 12 67 | 68 | # This is the same as... 69 | x = 5 70 | y = increase(x) 71 | print double(y) 72 | # 12 73 | 74 | print double(decrease(5)) 75 | # 8 76 | print increase(decrease(5)) 77 | # 5 78 | print double(double(5)): 79 | # 20 80 | ``` 81 | 82 | @@@ 83 | 84 | 85 | ###Method Calls 86 | 87 | A **method** is like a function but it is "bound" to an object. 88 | 89 | For example, the integers and strings we've been using have methods attached to them 90 | 91 | We can use the dir() function to see the methods of an object and help() to see what they do. 92 | 93 | ```python 94 | >>> sentence = 'the quick brown fox did the thing with the other thing' 95 | >>> print dir(sentence) 96 | # Lots of output 97 | >>> print sentence.capitalize() 98 | 'The quick brown fox did the thing with the other thing' 99 | >>> print sentence.count('the') 100 | 4 101 | >>> help(sentence.upper) 102 | # Lots of output 103 | ``` 104 | @@@ 105 | 106 | ###Let's Develop It 107 | 108 | Open a Python shell and define a string varaible 109 | 110 | Use 'dir(string_variable)' and the help() function to explore the various methods 111 | 112 | Hint: Like functions, some methods take arguments and others don't 113 | 114 | Hint: Use help(varname.methodname) on a method. It will tell you the arguments to use and the expected behavior 115 | 116 | Hint: Don't be afraid of errors. They are there to help you so read them carefully. 117 | 118 | ```python 119 | # Example 120 | name = 'beth' 121 | dir(name) 122 | help(name.capitalize) 123 | cap_name = name.capitalize() 124 | ``` 125 | 126 | Note: 5 minutes 127 | @@@ 128 | 129 | ###Lists 130 | 131 | A list is an ordered collection of elements 132 | 133 | In Python, a list is defined using `[ ]` with elements separated by commas, as in the following example 134 | 135 | ```python 136 | words = ['list', 'of', 'strings'] 137 | ``` 138 | 139 | A list can, but doesn't have to be of all one type. A list of one type is **homogenous** as opposed to a list of multiple types, which is **heterogeneous**. 140 | 141 | ```python 142 | # heterogenous list 143 | words = [0, 'list', 'of', 3, 'strings', 'and', 'numbers'] 144 | ``` 145 | Note: Block 2 - 30 Minutes 146 | @@@ 147 | 148 | ###List Methods 149 | 150 | Lists have several methods, the most useful of which is `append` 151 | A list can be created as an empty list and have values added to it with `append` 152 | ```python 153 | >>> to_dos = [] 154 | >>> to_dos.append('buy soy milk') 155 | >>> to_dos.append('install git') 156 | >>> print to_dos 157 | ['buy soy milk', 'install git'] 158 | ``` 159 | 160 | Therefore, lists are **mutable** 161 | 162 | This means that a list can change values during the duration of a program 163 | @@@ 164 | 165 | 166 | ###Iteration 167 | 168 | Lists and many other collections are **iterable**. 169 | 170 | Once defined, we can iterate on them, performing an action with each element 171 | 172 | ```python 173 | shipping_cost = 2.5 174 | prices = [3, 4, 5.25] 175 | 176 | costs = [] 177 | for price in prices: 178 | costs.append(price + shipping_cost) 179 | 180 | for cost in costs: 181 | print cost 182 | 183 | # Output 184 | # 5.5 185 | # 6.5 186 | # 7.75 187 | ``` 188 | @@@ 189 | 190 | 191 | ###Indexing 192 | 193 | An element can also be obtained from a list through **indexing** 194 | 195 | This allows us to obtain an element without iterating through the entire collection if we just want one value. 196 | 197 | To index on a collection, follow it immediately with `[index]`. (index here is a number, variable or expression) 198 | 199 | ```python 200 | >>> numbers = [10, 20, 30] 201 | >>> print numbers[0] 202 | 10 203 | ``` 204 | @@@ 205 | 206 | ###Indexing continued 207 | 208 | Lists and other collections in Python are zero indexed. This means that the number 0 refers to first element in the list. 209 | 210 | ```python 211 | >>> to_dos = ['install git', 'read email', 'make lunch'] 212 | >>> print to_dos[0] 213 | 'install git' 214 | >>> print to_dos[1] 215 | 'read email' 216 | >>> print to_dos[-1] 217 | 'make lunch' 218 | ``` 219 | 220 | Negative numbers mean "go back from the end this many". e.g. -1 is the last element, -2 is the penultimate 221 | 222 | An IndexError results if an index is too high or low for the number of elements 223 | @@@ 224 | 225 | 226 | ###Dictionaries 227 | 228 | A **dictionary** (sometimes called a "hashmap") is a collection of key/value pairs, defined with `{}` 229 | 230 | ```python 231 | menu_categories = { 232 | 'food': 'stuff you eat', 233 | 'beverage': 'stuff you drink', 234 | } 235 | ``` 236 | 237 | Think of words in a dictionary. The words are keys and the definitions are values. 238 | 239 | This dictionary would be indexed with strings such as 'food' and 'beverage' instead of integers like in a list 240 | @@@ 241 | 242 | 243 | ###Indexing on Dictionaries 244 | 245 | Dictionaries aren't literally for definitions. They represent a group of mappings. A mapping might be: menu items -> costs. 246 | 247 | We can also index on dictionaries. 248 | 249 | The most common indexes are strings, but this is not a hard requirement. 250 | 251 | ```python 252 | menu = { 253 | 'tofu': 4, 254 | } 255 | 256 | tofu_cost = menu['tofu'] 257 | # the tofu_cost variable is now equal to 4. 258 | ``` 259 | 260 | Indexing on a key that doesn't exist results in a KeyError 261 | 262 | If you aren't certain a key is present, you can use the 'get' method... 263 | @@@ 264 | 265 | 266 | ###Dictionary Methods 267 | 268 | Some of the most essential methods are *keys*, *values* and *items* 269 | 270 | ```python 271 | menu = { 272 | 'tofu': 4, 273 | 'pizza': 8, 274 | 'baguette': 3, 275 | } 276 | 277 | >>> print menu.get('pizza') 278 | 8 279 | >>> print menu.get('donuts', 5) 280 | 5 281 | >>> print menu.keys() 282 | ['tofu', 'pizza', 'baguette'] 283 | >>> print menu.values() 284 | [4, 8, 3] 285 | >>> print menu.items() 286 | [('tofu', 4), ('pizza', 8), ('baguette', 3)] 287 | ``` 288 | 289 | If a key isn't present, the get method will return a default value if provided, otherwise None 290 | @@@ 291 | 292 | ###The in operator 293 | 294 | The `in` operator is used to determine if an element is in a given collection 295 | 296 | For dictionaries, the keys are searched for the element. 297 | 298 | ```python 299 | >>> color = (255, 255, 0) 300 | >>> print(1 in color) 301 | False 302 | 303 | >>> menu = {'tofu': 4} 304 | >>> print('tofu' in menu) 305 | True 306 | ``` 307 | @@@ 308 | 309 | ###Let's Develop It 310 | * Improve our adventure game by adding a player inventory. The player should 311 | gain items they walk on them and they should be removed from the board. 312 | 313 | * The beginning of this program has been started and is available here as 314 | [game3.py](http://calebsmith.github.io/gdi-intro-python/examples/game3.py) 315 | 316 | * You'll also need to download the board.dat file to the same folder. 317 | [board.dat](http://calebsmith.github.io/gdi-intro-python/examples/board.dat) 318 | 319 | * If you are stuck ask the teacher or a TA for help. 320 | 321 | Note: Let's Develop It 30 minutes 322 | @@@ 323 | 324 | ###Tuples 325 | 326 | **Tuples** are like lists, but they are **immutable**. They are particularly good at storing collections of a fixed and predictable size. Use `()` to define tuples 327 | 328 | An x, y coordinate pair, or the RGB values of a color are good candidates for tuples. 329 | 330 | ```python 331 | point = (0, 1) 332 | x = point_a[0] 333 | y = point_a[1] 334 | 335 | # or, even better 336 | 337 | point = (0, 1) 338 | x, y = point_a 339 | # x is 0, y is 1 340 | ``` 341 | @@@ 342 | 343 | ###Sets 344 | **Sets** are unordered collections whose elements are unique. Therefore, adding a value to a set that already has it, does nothing. 345 | 346 | Sets can be created with comma separated elements enclosed in `{}` in Python 2.7 or greater. Very often, one will make a list and use the set() function 347 | 348 | Sets have an *add* method, which like append for lists, adds an element to a set. 349 | 350 | ```python 351 | >>> set_a = set([0, 3, 7]) 352 | >>> set_b = set([0, 4, 7]) 353 | >>> set_a.add(4) 354 | >>> print(set_a) 355 | set([0, 3, 4, 7]) 356 | >>> print(set_a.intersection(set_b)) 357 | set([0, 4, 7]) 358 | ``` 359 | 360 | Sets have nice methods for reasoning about their relationship to other sets. (Think Venn Diagram) 361 | @@@ 362 | 363 | ###Lists of ... Lists 364 | 365 | Lists can contain not only numbers or strings, but also other lists. 366 | 367 | Such a structure is said to be nested 368 | 369 | The following is a list of lists: 370 | 371 | This can be indexed successively. 372 | 373 | ```python 374 | game_board = [ 375 | ['O', 'X', ' '], 376 | [' ', 'X', ' '], 377 | [' ', ' ', ' '], 378 | ] 379 | 380 | print(game_board[0][1]) 381 | # outputs: 'X' 382 | ``` 383 | 384 | Note: Block 3 20 minutes 385 | @@@ 386 | 387 | 388 | ###Nested Lists continued 389 | 390 | A list can be appended to a list as well 391 | 392 | ```python 393 | mary_to_dos = ['eat', 'work', 'pick up laundry', 'care for baby', 'sleep'] 394 | fran_to_dos = ['eat', 'work', 'call plumber', 'sleep'] 395 | baby_to_dos = ['eat', 'sleep'] 396 | all_to_dos = [] 397 | all_to_dos.append(mary_to_dos) 398 | all_to_dos.append(fran_to_dos) 399 | all_to_dos.append(baby_to_dos) 400 | print(all_to_dos) 401 | 402 | for to_dos in all_to_dos: 403 | for to_do in to_dos: 404 | print(to_do) 405 | ``` 406 | If we want to flatten the to do's into one list, use **extend** 407 | 408 | What if we want the to do's to be unique? 409 | @@@ 410 | 411 | 412 | ###Lists of Dictionaries 413 | 414 | One of the most common and useful nested data structures, is a list of dictionaries 415 | 416 | ```python 417 | card_a = { 418 | 'suit': 'spades', 419 | 'number': 4, 420 | } 421 | card_b = { 422 | 'suit': 'hearts', 423 | 'number': 8, 424 | } 425 | hand = [card_a, card_b] 426 | 427 | print('The hand contains:') 428 | for card in hand: 429 | print('A', card['number'], 'of', card['suit']) 430 | ``` 431 | @@@ 432 | 433 | 434 | ###Dictionary of Lists 435 | 436 | A dictionary can also contain values that are themselves other collections, such as lists. 437 | 438 | Let's revisit the group of to do lists and find a better representation: 439 | 440 | ```python 441 | mary_to_dos = ['eat', 'work', 'pick up laundry', 'care for baby', 'sleep'] 442 | fran_to_dos = ['eat', 'work', 'call plumber', 'sleep'] 443 | baby_to_dos = ['eat', 'sleep'] 444 | all_to_dos = { 445 | 'mary': mary_to_dos, 446 | 'fran': fran_to_dos, 447 | 'baby': baby_to_dos, 448 | } 449 | for name, to_dos in all_to_dos.items(): 450 | print(name, 'needs to: ', to_dos) 451 | # Changing this later can be accomplished with 452 | all_to_dos['baby'].append('cry') 453 | ``` 454 | 455 | Now the to do lists can be indexed or modified by name 456 | 457 | @@@ 458 | 459 | 460 | ###Means of Combination 461 | 462 | Lists, dictionaries, sets, tuples, and other collections are all a means of combination. 463 | 464 | They can be freely combined to create the data structure needed for a particular problem 465 | 466 | Eg. A list of dictionaries with lists 467 | 468 | ```python 469 | all_tweets = [ 470 | { 471 | 'author': 'mary', 472 | 'handle': '@hadalittlelamb', 473 | 'date': '2013-01-22', 474 | 'tweets': [ 475 | 'at Loco Pops enjoying a Raspberry Sage popsicle', 476 | 'Learning Python is so much fun', 477 | 'Running late to Code and Coffee. #overslept', 478 | ], 479 | }, 480 | ] 481 | ``` 482 | @@@ 483 | 484 | ###Let's Develop It 485 | * Improve our adventure game by allowing a player with a key to pass through a 486 | door 487 | 488 | * The beginning of this program has been started and is available here as 489 | [game4.py](http://calebsmith.github.io/gdi-intro-python/examples/game4.py) 490 | 491 | * You'll also need to download the board.dat file to the same folder. 492 | [board.dat](http://calebsmith.github.io/gdi-intro-python/examples/board.dat) 493 | 494 | * If you are stuck ask the teacher or a TA for help. 495 | 496 | Note: Let's Develop It 30 minutes 497 | @@@ 498 | 499 | ###Builtins for collections 500 | 501 | Python provides several functions that help us work with these collections. 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 |
len()Given a collection, return its length
range()Create a list of integers in the range provided.
sorted()Given a collection, returns a sorted copy of that collection
enumerate()Returns a list of (index, element) from the list
zip()Given one or more iterables, returns a list of tuples with an element from each iterable
525 | @@@ 526 | 527 | 528 | ###Some Builtins 529 | 530 | ```python 531 | # Using len() - Determines length 532 | >>> print(len([1, 2])) 533 | 2 534 | # range() - Quickly creates a list of integers 535 | >>> print(range(5)) 536 | [0, 1, 2, 3, 4] 537 | >>> print(range(5, 10)) 538 | [5, 6, 7, 8, 9] 539 | >>> print(range(0, 10, 2)) 540 | [0, 2, 4, 6, 8] 541 | >>> print(range(9, 4, -1)) 542 | [9, 8, 7, 6, 5] 543 | # sorted() - Sort a given list 544 | >>> grades = sorted([93, 100, 60]) 545 | >>> print(grades) 546 | [60, 93, 100] 547 | ``` 548 | 549 | @@@ 550 | 551 | ###Builtins Examples continued 552 | 553 | ```python 554 | # enumerate() - Obtain the index and each element in a collection 555 | >>> to_dos = ['work', 'sleep', 'work'] 556 | >>> print(list(enumerate(to_dos)) 557 | [(0, 'work'), (1, 'sleep'), (2, 'work')] 558 | >>> for index, item in enumerate(to_dos): 559 | ... print(index, item) 560 | (0, 'work') 561 | (1, 'sleep') 562 | (2, 'work') 563 | # zip() 564 | >>> widths = [10, 15, 20] 565 | >>> heights = [5, 8, 12] 566 | >>> print(zip(widths, heights)) 567 | [(10, 5), (15, 8), (20, 12)] 568 | >>> for width, height in zip(widths, heights): 569 | ... print('Area is ', width * height) 570 | ('Area is ', 50) 571 | ('Area is ', 120) 572 | ('Area is ', 240) 573 | ``` 574 | 575 | Note: Let's develop it: 25 minutes 576 | @@@ 577 | 578 | ###Let's Develop It 579 | * Complete our game by allowing you to pick up a sword, battle a dragon and 580 | obtain the treasure. If the player has no sword, the dragon wins, otherwise 581 | the player wins. When the player obtains the gold, they have beaten the game 582 | 583 | * The beginning of this program has been started and is available here as 584 | [game5.py](http://calebsmith.github.io/gdi-intro-python/examples/game5.py) 585 | 586 | * You'll also need to download the board.dat file to the same folder. 587 | [board.dat](http://calebsmith.github.io/gdi-intro-python/examples/board.dat) 588 | 589 | * If you are stuck ask the teacher or a TA for help. 590 | 591 | Note: Let's Develop It 30 minutes 592 | @@@ 593 | 594 | ###Questions? 595 | -------------------------------------------------------------------------------- /set2/slides/part4.md: -------------------------------------------------------------------------------- 1 | ![Girl Develop It logo](../images/gdi_logo_badge.png) 2 | ###Intro to Python 3 | ####Class 4 4 | @@@ 5 | 6 | ###Review 7 | 8 | * Method calls 9 | 10 | * Combining lists and dictionaries 11 | 12 | * Builtins for collections 13 | 14 | @@@ 15 | 16 | ###Functions on Dictionaries 17 | 18 | ```python 19 | character = { 20 | 'x': 10, 21 | 'y': 20, 22 | 'health': 100, 23 | } 24 | 25 | def injure(character, damage): 26 | character['health'] = character['health'] - damage 27 | if character['health'] < 0: 28 | character['health'] = 0 29 | 30 | def heal(character, amount): 31 | character['health'] = character['health'] + amount 32 | if character['health'] > 100: 33 | character['health'] = 100 34 | ``` 35 | Note: Block 1 - Intro to Classes and OOP - 20 minutes 36 | @@@ 37 | 38 | ###Classes 39 | A **class** creates a new type of object. 40 | 41 | A class defines the attributes and methods of objects of that type 42 | 43 | Classes are used to create new objects of that type 44 | 45 | ```python 46 | class Character(): 47 | 48 | def __init__(self, x, y, health): 49 | self.x = x 50 | self.y = y 51 | self.health = health 52 | character = Character(10, 20, 100) 53 | ``` 54 | @@@ 55 | 56 | ###A Sense of Self 57 | The first argument to every method is **self**. 58 | 59 | self contains the attributes and methods for the current object 60 | 61 | ```python 62 | class Character(): 63 | 64 | def __init__(self, x, y, health): 65 | self.x = x 66 | self.y = y 67 | self.health = health 68 | character = Character(10, 20, 100) 69 | ``` 70 | @@@ 71 | 72 | ###The __init__ Method 73 | This method defines what the class should do when creating a new object. 74 | 75 | ```python 76 | class Character(): 77 | def __init__(self, x, y, health): 78 | self.x = x 79 | self.y = y 80 | self.health = health 81 | character_a = Character(10, 20, 100) 82 | character_b = Character(10, 20, 100) 83 | ``` 84 | To create a new Character, the syntax looks like a function call. These arguments are passed to the __init__ method 85 | 86 | @@@ 87 | 88 | ###Defining Methods 89 | A class also defines **methods**, which are functions that operate on objects of that type 90 | 91 | Assigning values to an attribute on self is how we **mutate** the object's state. 92 | 93 | ```python 94 | # inside the character class 95 | 96 | def heal(self, amount): 97 | self.health = self.health + amount 98 | if self.health > 100: 99 | self.health = 100 100 | 101 | def injure(self, amount): 102 | self.health = self.health - amount 103 | if self.health < 0: 104 | self.health = 0 105 | 106 | character = Character(10, 20, 100) 107 | character.injure(10) 108 | ``` 109 | @@@ 110 | 111 | ###Let's Develop It 112 | * Complete our game by allowing you to pick up a sword, battle a dragon and 113 | obtain the treasure. If the player has no sword, the dragon wins, otherwise 114 | the player wins. When the player obtains the gold, they have beaten the game 115 | 116 | * The beginning of this program has been started and is available here as 117 | [game6.py](http://calebsmith.github.io/gdi-intro-python/examples/game6.py) 118 | 119 | * You'll also need to download the board.dat file to the same folder. 120 | [board.dat](http://calebsmith.github.io/gdi-intro-python/examples/board.dat) 121 | 122 | * If you are stuck ask the teacher or a TA for help. 123 | 124 | * The finished game will look something like this: 125 | [game7.py](http://calebsmith.github.io/gdi-intro-python/examples/game7.py) 126 | 127 | * If you have extra time, consider making the player into a class as well 128 | 129 | Note: Let's Develop It 30 minutes 130 | @@@ 131 | 132 | ###Inheritance 133 | A class can **inherit** from another class. 134 | 135 | A class that inherits from another is called the "child class" and obtains the methods and attributes of its "parent" 136 | 137 | ```python 138 | class Mobile(object): 139 | """ 140 | An object with an x, y position, and methods for moving 141 | """ 142 | 143 | def __init__(self, x, y): 144 | self.x = x 145 | self.y = y 146 | 147 | def move_up(): 148 | self.y = self.y - 1 149 | # ... methods for move_down, move_left, and move_right 150 | ``` 151 | Note: Block 2 - Inheritance and Composition 20 Minutes 152 | @@@ 153 | 154 | ###Inheritance Continued 155 | The move_up method is **overridden** in the child class below: 156 | 157 | ```python 158 | class BoundedMobile(Mobile): 159 | """ 160 | An object with an x, y position, and methods for moving 161 | The x, y position must be within bounds 162 | """ 163 | 164 | def move_up(): 165 | self.y = self.y - 1 166 | if self.y < 0: 167 | self.y = 0 168 | ``` 169 | See [mobile.py](http://calebsmith.github.io/gdi-intro-python/examples/mobile.py) for a more complete example. 170 | 171 | @@@ 172 | 173 | ###What's Super about Super 174 | **super** is often helpful when writing methods that override the method of the parent class 175 | 176 | ```python 177 | class BoundedMobile(Mobile): 178 | """ 179 | An object with an x, y position, and methods for moving 180 | The x, y position must be within bounds 181 | """ 182 | 183 | def move_up(): 184 | super(BoundedMobile, self).move_up() 185 | if self.y < 0: 186 | self.y = 0 187 | ``` 188 | 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 189 | 190 | @@@ 191 | 192 | ###Composition 193 | Classes can also use the technique of **composition** 194 | 195 | This simply means that a given object contains other objects within it. 196 | 197 | This often leads to a clearer and simpler design 198 | 199 | ```python 200 | class Grid(object): 201 | 202 | def __init__(self, x_limit, y_limit): 203 | self.x_limit = x_limit 204 | self.y_limit = y_limit 205 | self.mobiles = [] 206 | 207 | def add_mobile(self, x, y): 208 | mob = BoundedMobile(x, y, self.x_limit, self.y_limit) 209 | mobs = self.mobiles.get((x, y), []) 210 | mobs.append(mob) 211 | self.mobiles[(x, y)] = mobs 212 | ``` 213 | @@@ 214 | 215 | ###Composition Continued 216 | Given the class on the previous slide, the following code creates mobiles within the grid object. (Complete code is available in the aforementioned [mobile.py](http://calebsmith.github.io/gdi-intro-python/examples/mobile.py)) 217 | 218 | ```python 219 | from mobile import Grid 220 | 221 | grid = Grid(7, 7) 222 | grid.add_mobile(1, 2) 223 | grid.add_mobile(0, 1) 224 | grid.add_mobile(0, 1) 225 | grid.display_grid() 226 | ``` 227 | @@@ 228 | 229 | ###Future Resources 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 |
[Python.org Documentation](http://docs.python.org/2/)Official Python Documentation
[Think Python Interactive](http://interactivepython.org/courselib/static/thinkcspy/index.html)Online Book with Live Code Runner
[Dive Into Python](http://www.diveintopython.net/toc/index.html)Online and print book with exercises.
[Learn Python the Hard Way](http://learnpythonthehardway.org/book/)Online and print book with exercises
[Google's Python Class](https://developers.google.com/edu/python/)Video lectures coupled with exercises
[New Coder](http://newcoder.io/tutorials/)Ideas for slightly larger projects and resources to get you started. Projects include accessing API's, scraping pages, writing IRC bots, and others.
[Girl Develop It](http://girldevelopit.com/)Local workshops, events, and coding sessions
261 | @@@ 262 | 263 | ###Questions? 264 | --------------------------------------------------------------------------------