├── .gitignore ├── LICENSE ├── README.md ├── lesson-1 └── first_class.py ├── lesson-10 ├── app.py ├── static │ └── main.css └── templates │ ├── forms │ └── name_form.html │ ├── index.html │ ├── post.html │ ├── root.html │ └── snippets │ ├── css.html │ ├── javascript.html │ └── snippet.html ├── lesson-2 └── states.py ├── lesson-3 ├── guess_a_number_loop.py ├── number_game.py ├── temp.py └── while_loop_example.py ├── lesson-4 ├── snow_man_explained.py └── snowman.py ├── lesson-5 ├── Baseball2013.csv ├── Hello.txt ├── create_file.py ├── html_write.py ├── new_write.py ├── people.csv ├── read_csv.py ├── read_hello.py ├── read_people.py ├── readfile.py ├── sample.txt └── write_csv.py ├── lesson-6 ├── README.md ├── restaurant.py ├── restaurant_spoiler.py └── slides.pdf ├── lesson-7 ├── find_member.py └── find_member_commented.py └── lesson-8 └── capitol_words.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .env 3 | *.pyc 4 | .idea 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 LindsayYoung 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Python Class 2 | ============ 3 | 4 | Sunlight's 2014 Summer Python class 5 | 6 | #Syllabus 7 | * [First class](#first-class): variables, types, list, dictionary 8 | * [Second class](#second-class): data types, data structures, conditional, user input, command line 9 | * [Third class](#third-class): command line, loops, range 10 | * [Fourth class](#fourth-class): functions 11 | * [Fifth class](#fifth-class): files, CSV reading and writing 12 | * [Sixth class](#sixth-class): classes and objects 13 | * [Seventh class](#seventh-class): APIs 14 | * [Eighth class](#eighth-class):CSV and API review and Start projects! 15 | * [Tenth class](#tenth-class):Flask 16 | 17 | [Additional resources](#additional-resources) 18 | 19 | *** 20 | # First Class! 21 | 06/18/2014 22 | [See lesson-1/first_class.py for more notes and code](https://github.com/LindsayYoung/python-class/blob/master/lesson-1/first_class.py) 23 | 24 | * Intro 25 | 26 | What is Python? 27 | * A Python program (or any program) is a list of instructions for you computer 28 | * Python is an intermediate language that makes these instructions somewhat more readable for humans 29 | * Like any language, Python has syntax and grammatical rules that you need to follow to facilitate understanding between yourself and the computer 30 | * Breaking these rules causes syntax errors that break your program 31 | 32 | Python is a free, open source language. For the beginning of the class we are going to use PythonAnywhere to run our code in our browser. 33 | * [PythonAnywhere](https://www.pythonanywhere.com) 34 | 1. run a line of code directly in the IPython console (we are using 2.7) 35 | 2. make a file and click save and run 36 | 3. make a file and and open the Bash console and type: python the_name_of_your_file.py 37 | 38 | (You can only have 2 consoles open at a time so you may have to close a console to see the console options) 39 | 40 | * The python prompt 41 | * “Hello World!” 42 | * Your first file! 43 | * “Hello World!” 44 | * The Bash prompt 45 | 46 | (If you missed this class, you can do the PythonAnywhere tutorial on the website.) 47 | 48 | ###Objects 49 | 50 | In Python, we work with objects. Thiat means we create, store and change objects in our programs. Useful objects are things like numbers and words. As we continue, we will make much more complex objects, but lets start with the basics. (See the [python documantation](https://docs.python.org/2/library/types.html) if you want to sneek a peek.) 51 | 52 | We can also create variables in python. You can think of creating variables as naming objects so you can remember them later and when you call them, they will be ready for you. Variable names can't start with numbers and they can't have spaces. 53 | 54 | Let's see a simple example of assigning a variable in the python console: 55 | ``` 56 | >>> greeting = "Hello" 57 | >>> print(greeting) 58 | Hello 59 | ``` 60 | 61 | In that code, we assigned the value, "Hello" to the variable name greeting. When you make variables, the name always goes to the left and the value that is being represented always goes to the right. We then used the print function to show us the value of greeting. 62 | 63 | We can create many objects for our programs that you can think of as numbers and words, but computers need a lot more specificity. So, in this case, we are talking about three types of objects in python. 64 | 65 | ###Types 66 | * integer- think of this as a whole number; no decimals. You can do math with this type of object but if you need the precision of decimals, say if you are doing division, don't use this because the computer will keep rounding the numbers to make them whole. 67 | * float- think of this as a decimal number. these are good for doing math. 68 | * string- think of strings as a collection of characters. These can be letters, numbers or symbols. If you have numbers as a string type, you can't do math with them. When you create a string, use single or double quotes. That was why "Hello" was quoted in the first example. 69 | 70 | Here are the functions we are going to use for types and changing types, We will use these functions by putting objects into the parenthesizes- 71 | * `type()` this will tell us the type of an object 72 | * `int()` this will make a number an integer 73 | * `str()` this will make an object into a string 74 | * `float()` this will make a number into a float 75 | 76 | Now, in the python shell, we will use some functions to find out what type an object is and change an object's type. If you want to save that change, you will need to reassign the variable, that tells the computer that the name you chose for your variable is representing another object, in this case a different type of object. 77 | 78 | ``` 79 | >>> type("Hello world!") 80 | 81 | >>> type(4) 82 | 83 | >>> type(3.5) 84 | 85 | >>> number = 7 86 | >>> type(number) 87 | 88 | >>> float(number) 89 | 7.0 90 | >>> type(number) 91 | 92 | >>> int(number) 93 | 7 94 | >>> str(number) 95 | '7' 96 | >>> int(number) 97 | 7 98 | >>> number = str(number) 99 | >>> type(number) 100 | 101 | >>> 102 | 103 | ``` 104 | 105 | ##data structures 106 | Lists and dictions are to ways to store your objects in a python program. You can think about lists as organized by the order of the objects and dictionaries as organized by the name of the object. 107 | 108 | ###Lists 109 | 110 | Here are some things to know about lists: 111 | * lists are ordered 112 | * use brackets [ ] 113 | * use commas between objects 114 | * add to the list with `.append()` 115 | * remove to a list with `.remove()` 116 | * order a list `.sort()` 117 | * you can grab an object in a list by knowing its location 118 | 119 | Let's look at a list example. For grabbing an item on the list we will need to know it's location in the list. One important thing to know is that computers don't count like people, they start counting at zero. So if you ask a computer to count something, it will go, 0, 1, 2, 3... 120 | To get an item in the list, 121 | 122 | I will add comments using `#`. In python, anything after the hash mark will not be interpreted as code. It is to tell other humans what is going on. (Also, if you follow along, don't type the dots.) 123 | 124 | ``` 125 | >>> # I will make a variable that is a list 126 | ... pets = ['cat', 'dog', 'bird', 'bunny', 'turtle', 'fish'] 127 | >>> # I will print the list 128 | ... print(pets) 129 | ['cat', 'dog', 'bird', 'bunny', 'turtle', 'fish'] 130 | >>> # print the third item in the list 131 | ... pets[2] 132 | 'bird' 133 | >>> # I will add to the list 134 | ... pets.append('tiger') 135 | >>> print(pets) 136 | ['cat', 'dog', 'bird', 'bunny', 'turtle', 'fish', 'tiger'] 137 | >>> # A tiger is not a pet, I will remove it 138 | >>> pets.remove('tiger') 139 | >>> print pets 140 | ['cat', 'dog', 'bird', 'bunny', 'turtle', 'fish'] 141 | ``` 142 | 143 | ###Dictionaries 144 | 145 | In the dictionaries you are used to, the information is organized by the word. Each word is paired with a definition. In Python dictionaries, you find each value by looking up its key. 146 | 147 | Here are some things to know about dictionaries: 148 | * key value pairs 149 | * use curly braces { } (we decided curly braces look like open dictionary books) 150 | * lookup by key 151 | * the key must be unique 152 | * use a colon between a key and a value, (the key always comes first) 153 | * use commas between key value pairs 154 | 155 | Let's look at an example of using a dictionary: 156 | ``` 157 | >>> # creating a dictionary where names are keys and the value is a number 158 | ... people = {'Mark': 14, 'Jose': 7, 'Pam':16, 'Jae':10} 159 | >>> # find the value associated with a key 160 | ... people['Pam'] 161 | 16 162 | >>> # lets add to a dictionary 163 | ... people['Amy'] = 11 164 | >>> print(people) 165 | {'Amy': 11, 'Jose': 7, 'Jae': 10, 'Pam': 16, 'Mark': 14} 166 | >>> #lets remove Mark 167 | >>> del people['Mark'] 168 | >>> print(people) 169 | {'Amy': 11, 'Jose': 7, 'Jae': 10, 'Pam': 16} 170 | >>> 171 | ``` 172 | 173 | ###Homework- 174 | [Homework inspired by Nicko](http://sunlightfoundation.com/blog/2010/12/02/sunlights-political-action-committee-pac-name-generator/) 175 | 176 | print a super PAC name using list indexes. Here is your list: 177 | 178 | pac_list = [ "Action", "Against", "Americans", "Awesome", "Citizens", "Committee", "Communist", "Country", "For", "Freedom", "Liberty", "PAC", "Patriots", "People", "Progressive", "Restore", "Results", "Sunlight", "Super", "Taxpayers", "United", "Values", "Votes", "Zealots", "Zombies"] 179 | 180 | Extra credit: find the random integer function to create a new name each time you run the program. (Hint: google “python random integer”) 181 | 182 | See [class code](https://github.com/LindsayYoung/python-class/blob/master/lesson-1/first_class.py) 183 | 184 | *** 185 | # Second Class! 186 | 06/18/2014 187 | 188 | ###Data types 189 | * string - letters or numbers as text 190 | * int - integer number 191 | * float - decimal number 192 | * use `type()` to discover the type of something 193 | * change type with `string()`, `int()`, `float()` 194 | new data type: 195 | * boolean - that is just a fancy way to say things that are `True` or `False` 196 | 197 | 198 | ###Data Structures 199 | 200 | ###lists 201 | * lists are ordered 202 | * use brackets [ ] 203 | * add to the list with `.append()` 204 | * remove to a list with `.remove()` 205 | * order a list `sorted()` 206 | * splice a list 207 | example: 208 | ``` 209 | >>> my_list = [4,3,2,6,1,5] 210 | >>> my_list[0] 211 | 4 212 | >>> my_list[-1] 213 | 5 214 | >>> my_list[2:4] 215 | [2, 6] 216 | >>> sorted(my_list) 217 | [1, 2, 3, 4, 5, 6] 218 | >>> sorted(my_list, reverse=True) 219 | [6, 5, 4, 3, 2, 1] 220 | >>> my_list.append(7) 221 | >>> print(my_list) 222 | [4, 3, 2, 6, 1, 5, 7] 223 | >>> my_list.remove(7) 224 | >>> print(my_list) 225 | [4, 3, 2, 6, 1, 5] 226 | ``` 227 | 228 | ###dictionaries 229 | * key value pairs 230 | * use curly braces { } (we decided curly braces look like open dictionary books) 231 | * lookup by key 232 | * the key must be unique 233 | * delete form a dictionary with del 234 | 235 | example: 236 | ``` 237 | >>> my_dictionary = {'DE':'Delaware', 'PA':'Pennsylvania'} 238 | >>> # there is no order in dictionaries, so no sorting 239 | >>> my_dictionary['DE'] 240 | 'Delaware' 241 | >>> my_dictionary['NJ'] = 'New Jersey' 242 | >>> print(my_dictionary) 243 | {'NJ': 'New Jersey', 'DE': 'Delaware', 'PA': 'Pennsylvania'} 244 | >>> del my_dictionary['NJ'] 245 | >>> print(my_dictionary) 246 | {'DE': 'Delaware', 'PA': 'Pennsylvania'} 247 | ``` 248 | ###flow control 249 | 250 | ###conditional statements 251 | We can check if something is true or false and make our program respond differently 252 | 253 | Here are some helpful operators to make comparisons 254 | * `==` equal 255 | * `!=` not equal 256 | * `>` greater than 257 | * `>=` greater than or equal to 258 | * `<` less than 259 | * `<=` less than or equal to 260 | * `not` means, not 261 | 262 | 'if' 263 | * `if` is a reserved word in Python that will trigger code to do something only if that condition is met. 264 | * make sure to put a colon after your if statement 265 | * if statements depend on consistent indentation to know what you want 266 | * to check for equality, use == (we use = for assigning a variable) 267 | example: 268 | ``` 269 | >>> python_class = 'fun' 270 | >>> if python_class == 'lame': 271 | ... print("This class is lame") 272 | ... 273 | >>> if python_class == 'fun': 274 | ... print("This class is as fun!") 275 | This class is fun! 276 | ``` 277 | 278 | 'else' 279 | * use else when you have a case not covered by if that you want to behave differently 280 | * remember indention and a colon! 281 | 282 | ``` 283 | >>> python_class = 'fun' 284 | >>> if python_class != 'fun': 285 | ... print("Python class is not fun") 286 | ... else: 287 | ... print("I love making computers do my bidding!") 288 | ... 289 | I love making computers do my bidding! 290 | ``` 291 | 292 | 'elif' 293 | 294 | The world is full of boundless opportunities and we might want to check for many things. 295 | ``` 296 | if my_bank_account > 1000000000: 297 | print('retire now') 298 | elif my_bank_account < 1: 299 | print('look for new job') 300 | else: 301 | print("keep on truckin'!") 302 | ``` 303 | Here is another example dedicated to Caitlin 304 | 305 | ###Take user input 306 | `raw_input()` 307 | We generally make programs and want them to respond to people and the real world. `raw_input()` will take a value from the user that you can use in your program. 308 | * add directions as a string in the parenthesis so you user knows what to do 309 | ``` 310 | >>> name = raw_input("what is your name?") 311 | what is your name?Lindsay 312 | >>> response = "Hello, " + name 313 | >>> print response 314 | Hello, Lindsay 315 | ``` 316 | Ready to make a real program? 317 | 318 | Let's look at: 319 | ###[lesson 2 code](https://github.com/LindsayYoung/python-class/blob/master/lesson-2/states.py) 320 | 321 | We also covered terminal and file systems because PythonAnywhere was down: 322 | ###Command line 323 | 324 | (Most of us Mac users used a Bash Terminal) 325 | 326 | 1) We opened terminal and typed `pwd`, then enter. (`pwd` stands for "print working directory") This printed out where we were in the file system. When we opened our terminal, we were in our home directory. People's home directory can be named anything in this example, my home directory is "home_directory." 327 | 328 | 2) We saved our file with the name 'states.py' and put it in a new folder called code in our home directory. The '.py' at the end of the file name tells the computer that the file is a python program. 329 | ``` 330 | home_directory 331 | | 332 | |-code 333 | |-states.py 334 | ``` 335 | 3) We went back to the terminal and typed `ls`, then enter. (`ls` stands for list) This listed everything in our home directory. We could find the code folder if it was properly saved in the home directory. 336 | 337 | Then, there were two ways of running the program: 338 | 339 | 1) We could run the program by typing `python code/states.py`, then enter. 'python' tells the terminal to run your program with python. Then, we gave it the location of the file with the folder name, a slash and the filename. 340 | 341 | 2) We can also move to the folder by typing 'cd code', then enter. (`cd` stands for "change directory" and "code" is the name of our folder) If we type 'ls' enter again, we can see our file `states.py`. Now that we are in the directory of our file, we can run the program by typing `python states.py`, then enter. 342 | 343 | Command line is not bad once you get the hang of it, but it takes some practice. 344 | 345 | This is a great resource from the Boston Python Workshop about to use a terminal to run python: 346 | * [for Mac computers](https://openhatch.org/wiki/Boston_Python_Workshop_8/Friday/OSX_Python_scripts) 347 | * [for Windows computers](https://openhatch.org/wiki/Boston_Python_Workshop_8/Friday/Windows_terminal_navigation) 348 | * [for Linux computers](https://openhatch.org/wiki/Boston_Python_Workshop_8/Friday/Linux_Python_scripts) 349 | 350 | Here's another resource, [Command Line Crash Corse](http://cli.learncodethehardway.org/book/), that explains command line basics. 351 | 352 | *** 353 | # Third Class! 354 | 07/02/2014 355 | ###Command line review 356 | 357 | The comand line is a way of operating system without GUI. GUI stands for grapical user interface and it is the point and click way that you are used to using a computer. 358 | 359 | When you are in the command line you are always in a place in your file system. To find out where you are you can use, `pwd` to print the current working directory. To see the folders and files directly below where you are you can use `ls` to list the files and folders of your current directory. Use `cd` to change your directory. 360 | 361 | To run a python program from command line, change to the directory of the file and type `python name_of_your_file.py` 362 | 363 | ### Loops 364 | 365 | Loops perform a set tasks that you give them over and over. It is extremely useful to write programs to do boring repetitive tasks for you. 366 | 367 | ### For loops 368 | 369 | "for" is a key word in Python that is used in loops. After 'for' you pass in a variable that you can use on each iteration of the loop. Then, you pass in the object you want to loop through. Like if statements, don't forget the colon and indentation. 370 | 371 | Here is an example: 372 | ``` 373 | >>>shopping_list = ["apple", "orange", "bread", "milk"] 374 | >>>for item in shoping_list: 375 | ... print item 376 | apple 377 | orange 378 | bread 379 | milk 380 | ``` 381 | That function went through each item in the list and printed it. 382 | 383 | Say you wanted to do some thing a set amount of times. You can use the `range()` function. Range takes an integer and creates a list that is as long as the integer you give it. 384 | 385 | Example: 386 | ``` 387 | >>> print range(5) 388 | [0, 1, 2, 3, 4] 389 | 390 | ``` 391 | 392 | The following program will print "hello" three times using range. 393 | ``` 394 | >>>for n in range(3): 395 | ... print("hello") 396 | hello 397 | hello 398 | hello 399 | ``` 400 | In the previous example we pass in 'n' because we are using it for counting. The variable you pass in can be anything you want. The first time through the loop, n is representing 0, the next time it is representing 1. finally, n represents, 2 the last item in the list provided by the range function. 401 | 402 | Dictionaries can be looped through as well. We will loop through each key in the dictionary using the `.keys()` function. 403 | ``` 404 | >>> person = {'first_name':'Jane', 'last_name':'Doe'} 405 | >>> for name in person.keys(): 406 | ... print name 407 | ... print person[name] 408 | ... 409 | first_name 410 | Jane 411 | last_name 412 | Doe 413 | ``` 414 | In that example, each loop name is the variable for the dictionary key that is being passed in. For each iteration of the loop when the program gets to `print name` the key is printed then, the next line `print person[name]` also executes because it is at the same indentation. In that line, we look up the value using the key in the dictionary and print the value. 415 | 416 | ### While loops 417 | 418 | 'while' is another way to control loops. Instead of doing something a set number of times, the program will keep looping until a condition is met. If the condition is never met, you have made an infinite loop and will need to use 'CTRL-C' to stop the loop. 419 | 420 | Don't forget indention and your colon. 421 | 422 | ``` 423 | >>> var = 5 424 | >>> while var < 8: 425 | ... print var 426 | ... var = var + 1 427 | ... 428 | 5 429 | 6 430 | 7 431 | ``` 432 | We added one to our variable, 'var', and and continued to do so until var was no longer less than 8. 433 | 434 | Lets try making a game based on a while loop. 435 | * Open a file in your text editor. Let's name it 'gessing_game.py' 436 | * Save that file in your code folder, so we can find it easily later 437 | * We will make something based on [guess_a_number_loop.py](https://github.com/LindsayYoung/python-class/blob/master/lesson-3/guess_a_number_loop.py) 438 | 439 | See the code we made during class [here].(https://github.com/LindsayYoung/python-class/blob/master/lesson-3/number_game.py) We also saw that using print statements can help in debugging when there is a logical error or a typo. 440 | 441 | *** 442 | # Fourth Class! 443 | 07/09/2014 444 | ###Functions 445 | Functions are contained, reusable bits of code. 446 | 447 | We have been using built-in functions. We give them inputs and they run a program (that we don't see) and return an output. Here are some useful functions: 448 | ``` 449 | >>> print("hello") 450 | hello 451 | >>> # len stands for length and gives you the length of an object like a string or list 452 | ... len("hello") 453 | 5 454 | >>> range(5) 455 | [0, 1, 2, 3, 4] 456 | >>> raw_input("example") 457 | examplehello 458 | 'hello' 459 | >>> str(1) 460 | '1' 461 | >>> int('1') 462 | 1 463 | 464 | ``` 465 | Now, it is time to build your own function. You probably noticed all of those functions use paresis. We will need paresis to call our function. "Calling a function" just means running the code in that function. 466 | 467 | In writing our function we need to use `def` to define it, name our function, have paresis, use a colon and put the code inside. As always, indentation is important! 468 | ``` 469 | def our_function(): 470 | print "hello" 471 | 472 | ``` 473 | We just wrote our first function! But how do we run it? 474 | 475 | We call the function like this: 476 | ``` 477 | our_function() 478 | ``` 479 | We can use functions to save us time on repetitive tasks: 480 | ``` 481 | # first, I will write my function 482 | def never_ending_song(): 483 | print("This is the song that never ends") 484 | print("It just goes on and on my friend") 485 | print("Some people started singing it not knowing what it was,") 486 | print("And they'll continue singing it forever just because . . .") 487 | 488 | # now I will call my function 489 | never_ending_song() 490 | 491 | # adding \n to create a line break 492 | answer = raw_input("Did you like that? \n") 493 | 494 | while answer == "yes": 495 | never_ending_song() 496 | answer = raw_input("Want some more? \n") 497 | 498 | print("\nOne more time for good measure \n") 499 | never_ending_song() 500 | ``` 501 | You can see we ran that same code in three different places in our script and only had to write it once! 502 | 503 | You may have noticed that the program is now not running in sequential order by line. When you call a function, it interrupts the sequential order of code and will go back to the function code and then return to where it was before and continue down the script. Remember to call the function after you define it. 504 | 505 | But perhaps, we need to to a similar thing but not the exact same thing. Functions can help us with that too. Like those built in functions we saw before, we can pass variables into our function. People call things that are being passed into a function, arguments. 506 | 507 | ``` 508 | def doubler(input): 509 | output = input * 2 510 | return output 511 | 512 | answer = doubler(4) 513 | 514 | print("answer") 515 | 516 | ``` 517 | Notice the first thing we did was define our function. Then, we called the function and passed in the argument 4. This takes out program back to our function, doubler, and tells our code input = 4. The program then multiplies 4 by 2 and assigns it to a variable, "output." Finally, our function returns our output value, 8. Since the program knows doubler returns 8, it assigns "answer" the value 8. Finally, the program prints 8 and is finished running. 518 | 519 | You might also ask why we did not just define the variables first rather than passing them in explicitly. The reason we need to pass in variables in to functions is that a function acts as a clean slate for your script. The variables you create normally outside your function don't exist inside your function. This concept about how far variables reach is called 'scope.' 520 | 521 | 522 | 523 | You can also pass in more than one argument: 524 | ``` 525 | def divide(numerator, denominator): 526 | answer = numerator/denominator 527 | return answer 528 | 529 | numerator = float(1) 530 | denominator = float(2) 531 | 532 | fraction = divide(numerator, denominator) 533 | 534 | print fraction 535 | 536 | ``` 537 | One more thing to note before we go on to our next activity. 538 | 539 | Find out if some thing is in a list, use `in` 540 | ``` 541 | designers = ['Olivia', 'Caitlin', 'Amy', 'Lola'] 542 | 543 | employee = raw_input("type a name and see if they are a Sunlight designer") 544 | 545 | if employee in designers: 546 | print "You named a designer" 547 | else: 548 | print "not a Sunlight designer" 549 | 550 | ``` 551 | (Pro tip, you can also use `in` to see if a character is in a string.) 552 | 553 | 554 | Now we can make another game "snowman" where you guess the letters in a word, or your snowman melts! 555 | 556 | 557 | Lets get started, [here](https://github.com/LindsayYoung/python-class/blob/master/lesson-4/snowman.py) 558 | 559 | *** 560 | # Fifth Class! 561 | 07/16/2014 562 | ###Files 563 | We have been using one file to write our programs. Now, we will be able to use many files for our programs. 564 | 565 | Here is a simple way to read a file. Let's start with a text file named sample.txt that says, "Hello! This is a sample document that we will read." 566 | 567 | ``` 568 | # This script assumes the file is in the same folder 569 | file = 'sample.txt' 570 | 571 | # this opens the file, it takes the file name as an argument 572 | txt = open(file) 573 | 574 | # this reads your file 575 | print txt.read() 576 | 577 | # it is a good idea to explicitly close your file 578 | txt.close() 579 | 580 | ``` 581 | There we go, we just read our first file! 582 | 583 | There were three main steps. Opening the document to get a file object, reading the file object and closing the file object. 584 | 585 | Now, lets create a file. 586 | ``` 587 | # open a file to write in, the "w" is for write 588 | file = open("newfile.txt", "w") 589 | 590 | # writing a line to the file 591 | file.write("hello \n") 592 | # writing another line to the file 593 | file.write("Here is another line\n") 594 | 595 | # closing file 596 | file.close() 597 | 598 | ``` 599 | There, we opened the file, wrote to the file and then closed it. 600 | 601 | Let's try to open this file another way. This way will make sure the file closes, so it is more secure. 602 | ``` 603 | # creating a file object 604 | with open("newfile2.txt", "w") as new_file: 605 | # writing a line to the file 606 | file.write("hello \n") 607 | # writing another line to the file 608 | file.write("Here is another line in another file.\n") 609 | # file closes when the loop ends 610 | ``` 611 | 612 | For reference, the 'w' was for write, but there are other commands that are useful for files. 613 | 'r' when the file will only be read. 'w' for only writing.'wb' write binary, 'rb' is write binary. 614 | 'a' opens the file for appending; any data written to the file is automatically added to the end. 615 | 'r+' opens the file for both reading and writing. 616 | 617 | ###CSV 618 | The `.csv` files are basically spreadsheets. You can make a csv by using excel or other spreadsheet program and saving the file as csv. (Be careful because some of the extra features you are used to like, highlighting and links, will not be saved.) 619 | 620 | `csv` stands for comma separated values. These files are great because of their simplicity. 621 | 622 | Here is a simple representation of a spreadsheet: 623 | 624 | | person | city | state | 625 | |---|---|---| 626 | | John | Denver | CO | 627 | | Katie | Chicago | IL | 628 | | Kevin | Washington | DC | 629 | 630 | If we save that file as a csv and open it in a text editor like sublime we will see that it looks like a list separated by commas. 631 | 632 | person,city,state 633 | John,Denver,CO 634 | Katie,Chicago,IL 635 | Kevin,Washington,DC 636 | 637 | Each item gets a comma and each line is on a separate line. 638 | 639 | We can use the [csv module](https://docs.python.org/2/library/csv.html) to easily read and write csv files. 640 | 641 | Now, lets see how to read a file. We will read the file and loop through the file. 642 | 643 | # import csv functionality 644 | import csv 645 | 646 | # opening in a way that will close the file when we are done 647 | with open('people.csv', 'rb') as csvfile: 648 | # reading file 649 | reader = csv.reader(csvfile) 650 | # looping through the lines in the csv 651 | for row in reader: 652 | print(row) 653 | print("now print the first three cells") 654 | print(row[0]) 655 | print(row[1]) 656 | print(row[2]) 657 | 658 | Let's look at an example of writing a csv 659 | 660 | # import to use csv capabilities in your program 661 | import csv 662 | 663 | # opening files in this way is good because it will make sure the file closes itself. 664 | with open('eggs.csv', 'wb') as csvfile: 665 | # creates the csv file 666 | writer = csv.writer(csvfile) 667 | # writes to the file 668 | writer.writerow(['a1', 'b1', 'c1']) 669 | writer.writerow(['a2', 'b2', 'c2']) 670 | writer.writerow(['a3', 'b3', 'c3']) 671 | # automatically closes 672 | 673 | That program will create a spreadsheet that looks something like this. 674 | 675 | |a1|b1|c1| 676 | |---|---|---| 677 | |a2|b2|c2| 678 | |a3|b3|c3| 679 | 680 | Lets use or csv writing skills to make a program that takes a csv and makes it into a html table. 681 | 682 | Here is what a html table looks like: 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 |
First nameLast nameAge
JillSmith50
EveJackson94
703 | 704 | HTML tags are always symmetrical. Each opening tag has a closing tag, the whole table is defined by the `` tags. The table heading is defined by the `` tags. `` is for each row and `
` is for each item in the heading. `
` is for each item in the row. 705 | 706 | We can use the [Baseball2013.csv](http://assets.sunlightfoundation.com.s3.amazonaws.com/reporting/uploads/Baseball%202013.csv) and make it into a table. 707 | * save the file in your code folder and save your code in the same folder. 708 | * read the baseball spreadsheet 709 | * loop through the lines of the csv and add tags 710 | * write the text with html to a file 711 | 712 | *** 713 | # Sixth Class! 714 | 07/23/2014 715 | 716 | Classes, objects, and more! 717 | 718 | See *lesson-6/slides.pdf* for class slides and *lesson-6/restaurant.py* for in-class exercises. 719 | 720 | *** 721 | # Seventh Class! 722 | 07/30/2014 723 | 724 | API! 725 | 726 | APIs are ways that you can ask a question to a computer and get an answer. 727 | 728 | Before we get started, you will need an API key to access Sunlight APIs. Go ahead and get one [here](http://sunlightfoundation.com/api/accounts/register/). It is free and straight forward. 729 | 730 | Now we are going to walk through using the query builder [here](http://tryit.sunlightfoundation.com/congress). 731 | 732 | To use the query builder: 733 | * put your API key at the top 734 | * click on the method you want; You can think of methods as different kinds of information. 735 | * fill in the query builder to create the call you want. 736 | 737 | In our example, we used the legislators/locate method. I then used 92886 as a example zip code in the zip box. 738 | 739 | Clicking on `try it` gave us a few things. 740 | * call- this is the url that we need to ask the api the question, "What legislators represent zip code 92886?" 741 | * response code- this is a way of seeing that it worked. It should be 200. You may have seen other response codes before, 404 means the server could not find your request and 500s mean a server error. See a list of response codes [here](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes). 742 | * response headers- is other information with the request. 743 | * response body- this is what you will see in your browser, it is the information you wanted in a format called json. We can use json as lists and dictionaries we have seen before. 744 | 745 | That will give us a lot of information about the legislators, but we can just ignore the information we don't want to use. 746 | 747 | Let's use the call to look at this information in a browser. 748 | 749 | To make it easy to read, lets find a browser plug-in that will put our requests into a more human-readable format. I recommend [jsonView](https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en) for crome browsers. You can google "json format browser plugin" and the name of your browser to find a useful plug-in. 750 | 751 | Ok, I will now put the call into the browser. 752 | 753 | Your call will look like this but you need to put in your API key: 754 | ``` 755 | congress.api.sunlightfoundation.com/legislators/locate?zip=92886&apikey=your_api_key_here 756 | ``` 757 | You should see that the results you get in your browser look like the response body we get in the response of the query builder. 758 | 759 | To make API calls, we need to create vary particular strings to ask a question of the data in the API. The query builder is a good way to understand how that call is supposed to look. 760 | 761 | We can see in our example call, that we had 762 | * the url to the api `congress.api.sunlightfoundation.com/` 763 | * the method we wanted, `legislators/locate` 764 | * a question mark separating the url and method from our parameters, `?` 765 | * parameters, `zip=92886&apikey=your_api_key_here` These are like the key value pairs we use in dictionaries but in this case it uses `=` to denote the key value pair and `&` in between the parameters. We passed in two parameters, the zip and apikey. An api key will gives access to all Sunlight's apis. 766 | 767 | We can even check out this call in the command line. 768 | You will get the same results if you open up your bash terminal and use `curl`. It is pronounced curl but I like to think of it as 'c', as in see url. It will show us the url. (Don't forget to substitute your API key. Don't type the '$' that signifies the beginning of a line in the terminal.) 769 | 770 | ``` 771 | $ curl "congress.api.sunlightfoundation.com/legislators/locate?zip=92886&apikey=your_api_key_here" 772 | ``` 773 | 774 | Did you see what that prints out? It is very cool! 775 | 776 | Now we have an idea of how APIs work, we can use python to automate this process. 777 | 778 | Let's look at making this process easier by using [requests](http://docs.python-requests.org/en/latest/). Requests is a library- a library is collection of code you can use. The requests library will format and retrieve the information we want for us. 779 | 780 | We will need to download and install requests to use it. You can download in your bash terminal by using: 781 | * `pip install requests`, if you have pip. 782 | * You can also use `easy_install requests`. 783 | * You can also `easy_install pip` and then, `pip install requests` 784 | 785 | *if you are on a mac and are having trouble with permissions, try 'sudo pip install requests' or 'sudo easy_install requests'. It will then ask you for the password you use to log into your computer. You won't see characters, but it will take your password. 786 | 787 | Pip is an easy way to install things. When you have to install things yourself, and don't just have a button to download like you are used to, installing things is not so fun. 788 | 789 | [Here](https://github.com/LindsayYoung/python-class/blob/master/lesson-7/find_member_commented.py) is the code we wrote in class that asks a user for a zip code and returns the name of the congress persons that represent that district. 790 | 791 | Also, See all the Sunlight API's [here](http://sunlightfoundation.com/api/) 792 | 793 | *** 794 | # Eighth Class! 795 | 08/06/2014 796 | 797 | ###API to csv 798 | 799 | The first part of class will be some additional API and csv practice and then we will talk about project groups. 800 | 801 | This first part of class is inspired by a press call I got recently. Once you know how to use APIs, it is often the easiest way to get the data you want. Then you want to share you data in an accessible way. 802 | 803 | Let's do some practice using the Capitol Words API to create spreadsheets filled with data. 804 | 805 | Then, we can alter the script to ask for user input so it will work for any API call with that method. 806 | 807 | [Here](https://github.com/LindsayYoung/python-class/blob/master/lesson-8/capitol_words.py) is the sample code. 808 | 809 | ###Projects! 810 | 811 | Let's have a discussion of how we are going to divide ourselves into project groups and what we are going to work on. 812 | 813 | *** 814 | # Tenth Class! 815 | 08/20/2014 816 | 817 | ###Flask 818 | 819 | This class will introduce the web microframework called Flask. We will cover instantiating the Flask class, python decorators, routes, templates, GET and POST requests, and how to structure your project directory. The class will more or less follow the Flask quickstart guide in the official documentation [http://flask.pocoo.org/docs/quickstart/](http://flask.pocoo.org/docs/quickstart/) leaving out the database hookup for next week. 820 | 821 | The only package you'll need to install is flask: `pip install flask` 822 | 823 | Flask uses a templating language called Jinja2 which is inspired from Django's templating language. You can read more about the syntax for this language at the official site [http://jinja.pocoo.org/](http://jinja.pocoo.org/). 824 | 825 | *** 826 | #Additional resources 827 | 828 | The official Python documentation: 829 | * [http://docs.python.org/](http://docs.python.org/) 830 | 831 | Additional practice: 832 | * [http://www.codecademy.com/](http://www.codecademy.com/) 833 | * [http://learnpythonthehardway.org/book/](http://learnpythonthehardway.org/book/) 834 | 835 | Book: 836 | * [Hello World](http://www.barnesandnoble.com/listing/2691811512844?r=1&cm_mmc=GooglePLA-_-Book_25To44-_-Q000000633-_-2691811512844) 837 | 838 | Other Resources: 839 | 840 | * Beginning guide [https://wiki.python.org/moin/BeginnersGuide/Programmers](https://wiki.python.org/moin/BeginnersGuide/Programmers) 841 | 842 | * A repository with good examples to use as reference[anthonydb/python-get-started](https://github.com/anthonydb/python-get-started) 843 | 844 | * A list of reserved words [python.org](https://docs.python.org/release/2.5.4/ref/keywords.html) 845 | 846 | 847 | -------------------------------------------------------------------------------- /lesson-1/first_class.py: -------------------------------------------------------------------------------- 1 | # I am a comment because there is a hash mark at the beginning of the line, the computer will not read it 2 | 3 | #### TYPES 4 | 5 | # string 6 | # you can use singe quotes or double quotes to denote a string 7 | # Below you see """Taxp"ayers'""" because it uses 3 double quotes I can put a quote in it 8 | "Happy" 9 | 10 | # interger, a non-deimal number 11 | 4 12 | 13 | # float, a decimal number - use floats for math 14 | 3.4 15 | 16 | # you can add like types together 17 | example = "the" + "9" 18 | 19 | # you cannot add unlike types together 20 | # if you try to run the next line, it will give you an error 21 | # examlple = "the" + 9 22 | 23 | ##### Variables 24 | # store a value 25 | answer = 3 + 4 26 | # the name on the left remembers what you give it 27 | # don't use spaces, or begin with a number 28 | something_scarry = "vampires" 29 | # here you print the value of the answer 30 | print(answer) 31 | print(something_scarry) 32 | 33 | #### Data structures 34 | 35 | # This is our list example, remember order matters! 36 | pac_list = [ 'Action', 'Against', 'Americans', 'Awesome', 37 | 'Citizens', 'Committee', 'Communist', 'Country', 'For', 38 | 'Freedom', 'Liberty', 'PAC', 'Patriots', 'People', 'Progressive', 39 | 'Restore', 'Results', 'Sunlight', 'Super', """Taxp"ayers'""", 'United', 40 | 'Values', 'Votes', 'Zealots', 'Zombies'] 41 | 42 | # to access an item in a list, count the items starting with 0 43 | # in the list above, 'Action' is the zeroth item 44 | action = pac_list[0] 45 | 46 | # This is concatonation, adding strings together our list item ar all stings so this works 47 | pac = pac_list[24] + " " + pac_list[1] + " " + pac_list[9] 48 | 49 | print(pac_list) 50 | 51 | # This is how you add to a list 52 | pac_list.append("Freedom Fighters") 53 | 54 | print(pac_list) 55 | # now freedom fighters is at the end of the list 56 | 57 | 58 | # This is an example of a dictionary, it useses key value pairs. The key must be unique 59 | # you can pair a key with a string, list, number, dictionary etc. 60 | random_dictionary = {"Lindsay": ["person", "teacher", 29], "Whinnie": "dog", "Lindsey": "person" } 61 | 62 | # this will print the value of "Lindsay" in the random_dictionary dictionary, which is the list ["person", "teacher", 29] 63 | print(random_dictionary["Lindsay"]) 64 | 65 | # this will print the value of "Whinnie" witch is "dog" 66 | print(random_dictionary["Whinnie"]) 67 | 68 | print(random_dictionary) 69 | 70 | # this is how you add to a dictionary 71 | random_dictionary["Lassie"] = "dog" 72 | print(random_dictionary) 73 | -------------------------------------------------------------------------------- /lesson-10/app.py: -------------------------------------------------------------------------------- 1 | # import all of the classes and modules we use in this file from the flask package 2 | from flask import Flask, render_template, request 3 | # create an instance of the Flask class with name = __name__ or the name of this file 4 | app = Flask(__name__) 5 | 6 | # set debug to true so we see error dumps in the browser 7 | app.debug = True 8 | 9 | # decorators to establish the URL route to reach the method below 10 | @app.route('/', methods=['GET']) 11 | @app.route('///', methods=['GET']) 12 | def index(name=None, color='blue', age=25): 13 | # create a list of dictionaries 14 | data = [{'name':'olivia','color':'red', 'age':26}, 15 | {'name':'tom','color':'green', 'age':34}] 16 | # add values from URL if present 17 | if name is not None: 18 | data.append({'name':name,'color': color, 'age':age}) 19 | # renders index.html from templates directory, passing in the names variable 20 | return render_template('index.html', data=data) 21 | 22 | # decorators to establish the URL route to reach the method below, accepts GET and POST 23 | @app.route('/post', methods=['GET','POST']) 24 | def post(): 25 | # checks if request method is POST 26 | if request.method == 'POST': 27 | # POST data is contained in request.form['variable_name'] 28 | full_name = request.form['firstname'] + " " + request.form['lastname'] 29 | return render_template("post.html", name=full_name) 30 | else: 31 | # otherwise another request method, probably a GET 32 | return render_template("post.html") 33 | 34 | # launch the app 35 | app.run() -------------------------------------------------------------------------------- /lesson-10/static/main.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | font-size: 72px; 3 | } 4 | 5 | .center-text 6 | { 7 | text-align:center; 8 | } 9 | 10 | #content { 11 | margin-left:auto; 12 | margin-right:auto; 13 | width:800px; 14 | } -------------------------------------------------------------------------------- /lesson-10/templates/forms/name_form.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | 6 | 7 |
-------------------------------------------------------------------------------- /lesson-10/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends 'root.html' %} 2 | 3 | {% block header %} 4 |

INDEX PAGE HEADER

5 | {% endblock %} 6 | 7 | {% block content %} 8 | {% for i in data %} 9 | {% with dict=i %} 10 | {% include 'snippets/snippet.html' %} 11 | {% endwith %} 12 | {% endfor %} 13 | {% endblock %} 14 | 15 | {% block footer %} 16 |

INDEX PAGE FOOTER

17 | {% endblock %} -------------------------------------------------------------------------------- /lesson-10/templates/post.html: -------------------------------------------------------------------------------- 1 | {% extends 'root.html' %} 2 | 3 | {% block content %} 4 | {% if name %} 5 |
Your full name is: {{ name }}
6 | {% else %} 7 | {% include 'forms/name_form.html' %} 8 | {% endif %} 9 | {% endblock %} 10 | 11 | {% block header %} 12 |

POST PAGE HEADER

13 | {% endblock %} 14 | 15 | {% block footer %} 16 |

POST PAGE FOOTER

17 | {% endblock %} -------------------------------------------------------------------------------- /lesson-10/templates/root.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | {% include 'snippets/css.html' %} 4 | {% include 'snippets/javascript.html' %} 5 | 6 | 7 |
8 | {% block header %}{% endblock %} 9 |
10 | 11 |
12 | {% block content %}{% endblock %} 13 |
14 | 15 |
16 | {% block footer %}{% endblock %} 17 |
18 | -------------------------------------------------------------------------------- /lesson-10/templates/snippets/css.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lesson-10/templates/snippets/javascript.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LindsayYoung/python-class/63821805dab826ab4c8b030c3cbdd6835435a3ce/lesson-10/templates/snippets/javascript.html -------------------------------------------------------------------------------- /lesson-10/templates/snippets/snippet.html: -------------------------------------------------------------------------------- 1 |

Hello {{ dict.name }} Age: {{ dict.age }} Color: {{ dict.color }}

-------------------------------------------------------------------------------- /lesson-2/states.py: -------------------------------------------------------------------------------- 1 | # We are going to write a program that gives the name and when it came into the union. 2 | # For example if a user gives this program "DE" the program should return Deleware, 1st 3 | 4 | state_dict = {'AL' : 'Alabama', 'AK' : 'Alaska', 'AZ' : 'Arizona', 'AR' : 'Arkansas', 'CA' : 'California','CO' : 'Colorado', 'CT' : 'Connecticut','DE' : 'Delaware','FL' : 'Florida','GA' : 'Georgia','HI' : 'Hawaii','ID' : 'Idaho','IL' : 'Illinois','IN' : 'Indiana','IA' : 'Iowa','KS' : 'Kansas','KY' : 'Kentucky','LA' : 'Louisiana','ME' : 'Maine','MD' : 'Maryland','MA' : 'Massachusetts','MI' : 'Michigan','MN' : 'Minnesota','MS' : 'Mississippi','MO' : 'Missouri','MT' : 'Montana','NE' : 'Nebraska','NV' : 'Nevada','NH' : 'New Hampshire','NJ' : 'New Jersey','NM' : 'New Mexico','NY' : 'New York','NC' : 'North Carolina','ND' : 'North Dakota','OH' : 'Ohio','OK' : 'Oklahoma','OR' : 'Oregon','PA' : 'Pennsylvania','RI' : 'Rhode Island','SC' : 'South Carolina','SD' : 'South Dakota','TN' : 'Tennessee','TX' : 'Texas','UT' : 'Utah','VT' : 'Vermont','VA' : 'Virginia','WA' : 'Washington','WV' : 'West Virginia','WI' : 'Wisconsin','WY' : 'Wyoming','DC' : 'District of Columbia'} 5 | 6 | # List of states in the order they joined the union 7 | state_list = ['Delaware', 'Pennsylvania', 'New Jersey', 'Georgia', 'Connecticut', 'Massachusetts', 'Maryland', 'South Carolina', 'New Hampshire', 'Virginia', 'New York', 'North Carolina', 'Rhode Island', 'Vermont', 'Kentucky', 'Tennessee', 'Ohio', 'Louisiana', 'Indiana', 'Mississippi', 'Illinois', 'Alabama', 'Maine', 'Missouri', 'Arkansas', 'Michigan', 'Florida', 'Texas', 'Iowa', 'Wisconsin', 'California', 'Minnesota', 'Oregon', 'Kansas', 'West Virginia', 'Nevada', 'Nebraska', 'Colorado', 'North Dakota', 'South Dakota', 'Montana', 'Washington', 'Idaho', 'Wyoming', 'Utah', 'Oklahoma', 'New Mexico', 'Arizona', 'Alaska', 'Hawaii'] 8 | 9 | # Ask the user for input and provide a prompt that explains we need a state abbreviation 10 | # Make sure the user input is assigned to a variable 11 | state = raw_input("Give me a state abbreviation ") 12 | 13 | # Check if the abbreviation is in the state_dictionary 14 | # If it is not in the state dictionary, give an error message of your choosing and exit() 15 | if not state_dict.has_key(state): 16 | print("Error not in dictionary") 17 | exit() 18 | 19 | print("good job that is a state") 20 | 21 | # Look up the abbreviation in the state_dictionary to get the full name 22 | # Make sure full name is assigned to a variable 23 | state_name = state_dict[state] 24 | 25 | # Find the index of the item in the list 26 | # Because index will start counting at zero, we want to add 1 to the index to get its order of admission 27 | order = state_list.index(state_name) 28 | order = order + 1 29 | 30 | # Format the order as a string 31 | order = str(order) 32 | 33 | # extra credit: (hint treat the string like a list) 34 | # if it ends in a "2" add "nd" at the end of the string 35 | # else if it ends in a "1" add "st" at the end of the string 36 | # else if it ends in a "3" add "rd" at the end of the string 37 | # else, add a "th" to the end of the string 38 | 39 | # Print the full name of the state and order that it was accepted into the union 40 | print_statement = "Your state is " + state_name + " the order is " + order 41 | print(print_statement) 42 | 43 | 44 | # Please note that this example is not the most efficient way of attacking this problem, but it will help you practice skills you need later 45 | -------------------------------------------------------------------------------- /lesson-3/guess_a_number_loop.py: -------------------------------------------------------------------------------- 1 | # You use import to get additional python functionality that is already installed but not loaded automatically 2 | import random 3 | 4 | # create a random integer between 1 and 99 5 | secret = random.randint(1,99) 6 | 7 | # creating these variables to keep track of gesses and tries 8 | guess = 0 9 | tries = 0 10 | 11 | print("I am a magical leprechaun, to win my pot of gold, guess my number between 1 and 99. You only get 6 guesses.") 12 | 13 | while guess != secret and tries <6: 14 | guess = raw_input("do you know the number?") 15 | if guess < secret: 16 | raw_input(str(guess) + "- that's too low!") 17 | elif guess > secret: 18 | raw_input(str(guess) + " is too high!") 19 | tries = tries + 1 20 | 21 | if guess == secret: 22 | print("First they were after my lucky charms, now you get my gold too!") 23 | else: 24 | print("I am keeping my pot of gold- it is magically delicious") 25 | -------------------------------------------------------------------------------- /lesson-3/number_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # create a random integer between 1 and 10 4 | secret = random.randint(1,10) 5 | 6 | guess = int(raw_input("Pick a number between 1 and 10!")) 7 | tries = 4 8 | 9 | if guess == secret: 10 | print("WOw YOu are good!") 11 | 12 | while guess != secret and tries > 0: 13 | if guess > secret: 14 | print("Your guess was too high") 15 | else: 16 | print("Your guess was too low") 17 | guess = raw_input("Pick a number between 1 and 10!") 18 | guess = int(guess) 19 | tries = tries - 1 20 | 21 | 22 | 23 | if guess == secret: 24 | print("You WON!!!") 25 | else: 26 | print("sorry, try again!") 27 | 28 | 29 | -------------------------------------------------------------------------------- /lesson-3/temp.py: -------------------------------------------------------------------------------- 1 | temp = int(raw_input("What is the tempature? ")) 2 | humidity = raw_input("is humidity high or low ") 3 | tornado_warning = raw_input("Do you see a tornado? ") 4 | # elsif example 5 | 6 | # I want a special message for extreme conditions 7 | if (temp >= 100) and (humidity == "high"): 8 | print("Heat advisory due to humidity and high tempature. Use extra caution") 9 | # Want to print this if it is humid. I don't want to print the first if and this statement because that would be repetitive. 10 | elif (temp > 80) and (humidity == "high"): 11 | print("Heat advisory due to humidity") 12 | # Want to print this if it is hot but not if it is hot and humid. If it is hot and humid we already gave the "extra caution" message. 13 | elif temp > 100: 14 | print("Heat advisory due to tempture") 15 | # we checked all the conditions for a heat advisory and none of them applied 16 | else: 17 | print("No heat advisory") 18 | 19 | # If these were all if statements, then on the very hot humid days we would too many repetitive messages. 20 | # Another benefit is that our else statments keeps track of three different ways there could be a heat advisory. 21 | 22 | # this additional contition will always be evaluated, regardless of the previous statement 23 | if tornado_warning == 'yes': 24 | print("Stop worring about the heat and take cover!") 25 | -------------------------------------------------------------------------------- /lesson-3/while_loop_example.py: -------------------------------------------------------------------------------- 1 | # example of while loop 2 | 3 | # take input from the user 4 | someInput = raw_input("type 3 to continue anything else to quit") 5 | 6 | while someInput == '3': 7 | print("thank you for the 3, It was very kind of you") 8 | print("type 3 to continue, anything else to quit") 9 | someInput = raw_input() 10 | 11 | print("How dare you, that is not a 3, I QUIT!") 12 | -------------------------------------------------------------------------------- /lesson-4/snow_man_explained.py: -------------------------------------------------------------------------------- 1 | # Make a word guessing game using functions 2 | 3 | # these are strings that I will put into a list 4 | snow_1 = " _ " 5 | snow_2 = " _|=|_ " 6 | snow_3 = " ('') " 7 | snow_4 = ">--( o )--<" 8 | snow_5 = " ( o ) " 9 | 10 | # this is the list of snow man strings 11 | snow_man = [snow_1, snow_2, snow_3, snow_4, snow_5] 12 | 13 | # defining my functions first 14 | 15 | # this function takes in the snow_man list 16 | def print_snow(snow_man): 17 | # looping through each item in the snow_man list 18 | for snow in snow_man: 19 | # printing snow, the item we are looping through 20 | print snow 21 | 22 | # this is the function that prints out the answer in blank line format like: _ _ _ _ _ _ 23 | # (you will want to modify this function to print letters to replace the blanks as you go) 24 | def print_answer(answer): 25 | # I am defining the varible output before I start adding to it in my loop 26 | output = '' 27 | # looping through each letter in answer 28 | for letter in answer: 29 | # Adding a dash and a space to output for each letter 30 | output = output + "_ " 31 | # printing output 32 | print output 33 | 34 | # defining variables, They must be defined before we use them later 35 | 36 | # here is the answer to our program 37 | answer = "python" 38 | 39 | # this is an empty list for guesses 40 | correct_guesses = [] 41 | 42 | # This is the while loop that will keep going as long as the length of the answer is not equal to the length of correct guesses 43 | while len(answer) != len(correct_guesses): 44 | # prining banter 45 | print("I am thinking of a word ") 46 | # calling the print answer funciton 47 | print_answer(answer) 48 | # asking for a letter guess 49 | guess = raw_input("guess a letter") 50 | # if the guess is in the answer 51 | if guess in answer: 52 | print "You got it" 53 | # add the answer to the list of correct guesses 54 | correct_guesses.append(guess) 55 | # incorrect guess 56 | else: 57 | # calling the print_snow function and passing in our snow_man list 58 | print_snow(snow_man) 59 | # removing a piece of the snowman by getting rid of the first thing in the list 60 | snow_man.remove(snow_man[0]) 61 | # or you can use-- 62 | # snow_man.pop(0) 63 | -------------------------------------------------------------------------------- /lesson-4/snowman.py: -------------------------------------------------------------------------------- 1 | # Make a word guessing game using functions 2 | snow_1 = " _ " 3 | snow_2 = " _|=|_ " 4 | snow_3 = " ('') " 5 | snow_4 = ">--( o )--<" 6 | snow_5 = " ( o ) " 7 | 8 | 9 | snow_man = [snow_1, snow_2, snow_3, snow_4, snow_5] 10 | 11 | def print_snow(snow_man): 12 | for snow in snow_man: 13 | print snow 14 | 15 | def print_answer(answer): 16 | output = '' 17 | for letter in answer: 18 | output = output + "_ " 19 | print output 20 | 21 | answer = "python" 22 | 23 | correct_guesses = [] 24 | 25 | while len(answer) != len(correct_guesses): 26 | print("I am thinking of a word ") 27 | print_answer(answer) 28 | 29 | guess = raw_input("guess a letter") 30 | 31 | if guess in answer: 32 | print "You got it" 33 | correct_guesses.append(guess) 34 | else: 35 | print_snow(snow_man) 36 | snow_man.remove(snow_man[0]) 37 | # or you can use-- 38 | # snow_man.pop(0) 39 | 40 | -------------------------------------------------------------------------------- /lesson-5/Baseball2013.csv: -------------------------------------------------------------------------------- 1 | Team,Total Contributions Baltimore,"$1829200" Boston,"$1367245" Chicago WS,"$260543" Cleveland,"$22272" Detroit,"$186925" Houston,"$55050" Kansas City,"$57902" LA Angels,"$126250" Minnesota,"$644016" NY Yankees,"$43220" Oakland,"$5000" Seattle,"$488751" Tampa Bay,"$20250" Texas,"$117350" Toronto,$0 Arizona,"$366398" Atlanta,"$35100" Chicago Cubs,"$13917827" Cincinnati,"$360565" Colorado,"$246089.6" LA Dodgers,"$372250" Miami,"$178550" Milwaukee,"$1030597" NY Mets,"$188394" Philadelphia,"$246700" Pittsburgh,"$28000" San Diego,"$92950" San Francisco,"$1566494" St. Louis,"$121637" Washington,"$81375" -------------------------------------------------------------------------------- /lesson-5/Hello.txt: -------------------------------------------------------------------------------- 1 | Hello -------------------------------------------------------------------------------- /lesson-5/create_file.py: -------------------------------------------------------------------------------- 1 | file = open("newfile.txt", "w") 2 | 3 | file.write("hello \n") 4 | 5 | file.write("here we go!") 6 | 7 | file.close() 8 | -------------------------------------------------------------------------------- /lesson-5/html_write.py: -------------------------------------------------------------------------------- 1 | import csv 2 | 3 | html = "" 4 | # writing out the header of the html 5 | html = html + "\n" 6 | 7 | with open("eggs.csv", "rU") as csvfile: 8 | reader = csv.reader(csvfile) 9 | for row in reader: 10 | # we replaced this written out line with a loop below 11 | # html = html + " 12 | html = html + "" 13 | for data in row: 14 | html = html + "" 15 | html = html +"\n" 16 | 17 | html = html + "
title1title2title3
" + row[0] + "" + row[1] + "" + row[2] + "
" + data + "
" 18 | 19 | print(html) -------------------------------------------------------------------------------- /lesson-5/new_write.py: -------------------------------------------------------------------------------- 1 | with open("newfile2.txt", "w") as new_file: 2 | new_file.write("First line of code. ") 3 | new_file.write("second line second line.") -------------------------------------------------------------------------------- /lesson-5/people.csv: -------------------------------------------------------------------------------- 1 | name,city,state 2 | John,Denver,CO 3 | Katie,Chicago,IL 4 | Kevin,Washington,DC -------------------------------------------------------------------------------- /lesson-5/read_csv.py: -------------------------------------------------------------------------------- 1 | import csv 2 | # we are using U so that it can read from excel 3 | with open('sheet.csv', 'rU') as csvfile: 4 | reader = csv.reader(csvfile) 5 | for row in reader: 6 | print(row) 7 | print(row[0]) 8 | print(row[1]) 9 | print(row[2]) -------------------------------------------------------------------------------- /lesson-5/read_hello.py: -------------------------------------------------------------------------------- 1 | file = "Hello.txt" 2 | 3 | txt = open(file) 4 | 5 | print( txt.read() ) 6 | 7 | txt.close() -------------------------------------------------------------------------------- /lesson-5/read_people.py: -------------------------------------------------------------------------------- 1 | # import csv functionality 2 | import csv 3 | 4 | # opening in a way that will close the file when we are done 5 | with open('people.csv', 'rb') as csvfile: 6 | # reading file 7 | reader = csv.reader(csvfile) 8 | # looping through the lines in the csv 9 | for row in reader: 10 | print(row) 11 | print("now print the first three cells") 12 | print(row[0]) 13 | print(row[1]) 14 | print(row[2]) -------------------------------------------------------------------------------- /lesson-5/readfile.py: -------------------------------------------------------------------------------- 1 | # This script assumes the file is in the same folder 2 | file_name = 'sample.txt' 3 | 4 | # this opens the file, it takes the file name as an argument 5 | txt = open(file_name) 6 | 7 | # this reads your file 8 | print txt.read() 9 | 10 | # it is a good idea to explicitly close your file 11 | txt.close() -------------------------------------------------------------------------------- /lesson-5/sample.txt: -------------------------------------------------------------------------------- 1 | Hello! This is a sample document that we will read. -------------------------------------------------------------------------------- /lesson-5/write_csv.py: -------------------------------------------------------------------------------- 1 | import csv 2 | # wb for writing 3 | with open("eggs.csv", "wb") as csvfile: 4 | writer = csv.writer(csvfile) 5 | writer.writerow(['a1', 'b1', 'c1']) 6 | writer.writerow(['a2', 'b2', 'c2']) -------------------------------------------------------------------------------- /lesson-6/README.md: -------------------------------------------------------------------------------- 1 | # Objects 2 | 3 | Objects are things in Python. We'll go over them in class. 4 | 5 | ## Exercises 6 | 7 | Congratulations! You are now a restaurateur. All of the existing restaurant management software out there is garbage, so since you know how to write code in Python, you're going to custom build a system for yourself! 8 | 9 | ### In Class 10 | 11 | 1. The first method we'll implement, *print_menu*, will print out all of the menu items and their prices. 12 | 13 | 1. The next method we'll be writing is the *has_item* method. It should simply return True or False depending on if a particular item is on the menu. 14 | 15 | 1. *take_order* is going to be one of the more challenging methods. It takes an item name and an amount of money and can do one of three things: 16 | * print an "item doesn't exist" message 17 | * print a "not enough money" message 18 | * record the transaction and return the amount of change 19 | 20 | 1. Implement *take_big_order* which accepts a list of items to order. 21 | 22 | 1. *print_sales_report* prints out the total number of each item ordered and a total amount earned so far. 23 | 24 | 25 | ### Homework 26 | 27 | 1. Add an inventory for each item and adjust the *has_item* and *take_order* methods accordingly. 28 | 29 | 1. Add a LawAbidingRestaurant subclass of Restaurant that accepts an additional parameter to *\_\_init\_\_* that takes a tax percentage. 30 | * Override *print_menu* to include totals with tax, example: 31 | 32 | `PB&J ........ 1.99 (2.09)` 33 | 34 | * Override *take_order* to charge the tax rate 35 | -------------------------------------------------------------------------------- /lesson-6/restaurant.py: -------------------------------------------------------------------------------- 1 | class Restaurant(object): 2 | 3 | def __init__(self, name, menu): 4 | self.name = name 5 | self.menu = menu 6 | self.items_ordered = [] 7 | 8 | 9 | def print_menu(self): 10 | """ Print the entire menu. Example: 11 | 12 | PB&J ... 1.99 13 | Cheeseburger ... 3.75 14 | """ 15 | # YOUR CODE HERE 16 | 17 | 18 | def has_item(self, item): 19 | """ Check if the restaurant has an item by the given name """ 20 | # YOUR CODE HERE 21 | return False 22 | 23 | 24 | def take_order(self, item, money): 25 | """ Take an order for item, given a certain amount of money. 26 | 27 | If the item doesn't exist, print "Sorry, we don't have ". 28 | 29 | If the cost of the item is greater than the money provided, print 30 | "Sorry, costs " (eg. "Sorry, PB&J costs 1.99") 31 | 32 | If the order is successful, record the order and return the person's 33 | change (money - price) to them. 34 | """ 35 | # YOUR CODE HERE 36 | return money 37 | 38 | 39 | def take_big_order(self, items, money): 40 | """ Works just like take_order but takes an order for multiple items 41 | 42 | Error if money cannot pay for all items: 43 | "Total price of items is , you paid " 44 | 45 | Error if any items are not on menu: 46 | "Sorry, we don't have " 47 | 48 | In both error cases, no order should take place (no money exchanged) 49 | 50 | If the order is successful, record the order and return the person's 51 | change (money - price) to them. 52 | """ 53 | # YOUR CODE HERE 54 | return money 55 | 56 | 57 | def print_sales_report(self): 58 | """ Print daily sales report. Example: 59 | 60 | PB&J : 2 61 | Cheeseburger : 5 62 | Milkshake : 3 63 | ----- 64 | Total: $27.23 65 | """ 66 | # YOUR CODE HERE 67 | 68 | 69 | if __name__ == '__main__': 70 | 71 | menu = { 72 | 'ShackBurger': 4.85, 73 | 'Fries': 2.85, 74 | 'Shake': 5.00, 75 | } 76 | 77 | r = Restaurant('Shake Shack', menu) 78 | 79 | print("") 80 | 81 | print("------------\nThe menu\n------------") 82 | r.print_menu() 83 | 84 | print("") 85 | 86 | print("%s has Fries: %s" % (r.name, r.has_item('Fries'))) 87 | print("%s has BBQ: %s" % (r.name, r.has_item('BBQ'))) 88 | 89 | print("") 90 | 91 | change = r.take_order('ShackBurger', 10.00) 92 | if change: 93 | print("Ordered a ShackBurger and got %0.2f in change" % change) 94 | 95 | order = ('ShackBurger', 'ShackBurger', 'Fries', 'Shake') 96 | change = r.take_big_order(order, 50.00) 97 | if change: 98 | print("Ordered %s and got %0.2f in change" % (", ".join(order), change)) 99 | 100 | print("") 101 | 102 | print("------------\nSales Report\n------------") 103 | r.print_sales_report() 104 | 105 | 106 | # test some error cases 107 | 108 | print("") 109 | print("------------\nTest Errors\n------------") 110 | print "\t%0.2f in change" % r.take_order('Kale Salad', 5.00) 111 | print "\t%0.2f in change" % r.take_order('ShackBurger', 0.25) 112 | print "\t%0.2f in change" % r.take_big_order(('ShackBurger', 'Kale Salad'), 5.00) 113 | print "\t%0.2f in change" % r.take_big_order(('ShackBurger', 'Fries'), 5.00) 114 | -------------------------------------------------------------------------------- /lesson-6/restaurant_spoiler.py: -------------------------------------------------------------------------------- 1 | class Restaurant(object): 2 | 3 | def __init__(self, name, menu): 4 | self.name = name 5 | self.menu = menu 6 | self.items_ordered = [] 7 | 8 | 9 | def print_menu(self): 10 | """ Print the entire menu. Example: 11 | 12 | PB&J ... 1.99 13 | Cheeseburger ... 3.75 14 | """ 15 | 16 | for item, price in self.menu.items(): 17 | print("%s ... %0.2f" % (item, price)) 18 | 19 | 20 | def has_item(self, item): 21 | """ Check if the restaurant has an item by the given name """ 22 | 23 | return item in self.menu 24 | 25 | 26 | def take_order(self, item, money): 27 | """ Take an order for item, given a certain amount of money. 28 | 29 | If the item doesn't exist, print "Sorry, we don't have ". 30 | 31 | If the cost of the item is greater than the money provided, print 32 | "Sorry, costs " (eg. "Sorry, PB&J costs 1.99") 33 | 34 | If the order is successful, record the order and return the person's 35 | change (money - price) to them. 36 | """ 37 | 38 | if not self.has_item(item): 39 | print("Sorry, we don't have %s" % item) 40 | return money 41 | 42 | price = self.menu[item] 43 | 44 | if price > money: 45 | print("Sorry, %s costs %0.2f" % (item, price)) 46 | return money 47 | 48 | self.items_ordered.append(item) 49 | 50 | return money - price 51 | 52 | 53 | def take_big_order(self, items, money): 54 | """ Works just like take_order but takes an order for multiple items 55 | 56 | Error if money cannot pay for all items: 57 | "Total price of items is , you paid " 58 | 59 | Error if any items are not on menu: 60 | "Sorry, we don't have " 61 | 62 | In either error case, no order should take place (no money exchanged) 63 | 64 | If the order is successful, record the order and return the person's 65 | change (money - price) to them. 66 | """ 67 | 68 | for item in items: 69 | if not self.has_item(item): 70 | print("Sorry, we don't have %s" % item) 71 | return money 72 | 73 | total_price = sum(self.menu[item] for item in items) 74 | 75 | if total_price > money: 76 | print("Total price of items is %0.2f, you paid %0.2f" % (total_price, money)) 77 | return money 78 | 79 | self.items_ordered.extend(items) 80 | 81 | return money - total_price 82 | 83 | 84 | def print_sales_report(self): 85 | """ Print daily sales report. Example: 86 | 87 | PB&J : 2 88 | Cheeseburger : 5 89 | Milkshake : 3 90 | ----- 91 | Total: $27.23 92 | """ 93 | total_price = 0 94 | report = {} 95 | 96 | for item in self.items_ordered: 97 | 98 | price = self.menu[item] 99 | 100 | if item not in report: 101 | report[item] = 0 102 | 103 | report[item] += 1 104 | total_price += price 105 | 106 | for item, count in report.items(): 107 | print("%s : %d" % (item, count)) 108 | print("-----") 109 | print("Total: $%0.2f" % total_price) 110 | 111 | 112 | if __name__ == '__main__': 113 | 114 | menu = { 115 | 'ShackBurger': 4.85, 116 | 'Fries': 2.85, 117 | 'Shake': 5.00, 118 | } 119 | 120 | r = Restaurant('Shake Shack', menu) 121 | 122 | print("") 123 | 124 | print("------------\nThe menu\n------------") 125 | r.print_menu() 126 | 127 | print("") 128 | 129 | print("%s has Fries: %s" % (r.name, r.has_item('Fries'))) 130 | print("%s has BBQ: %s" % (r.name, r.has_item('BBQ'))) 131 | 132 | print("") 133 | 134 | change = r.take_order('ShackBurger', 10.00) 135 | if change: 136 | print("Ordered a ShackBurger, paid 10.00 and got %0.2f in change" % change) 137 | 138 | order = ('ShackBurger', 'ShackBurger', 'Fries', 'Shake') 139 | change = r.take_big_order(order, 50.00) 140 | if change: 141 | print("Ordered %s, paid 50.00 and got %0.2f in change" % (", ".join(order), change)) 142 | 143 | print("") 144 | 145 | print("------------\nSales Report\n------------") 146 | r.print_sales_report() 147 | 148 | 149 | # test some error cases 150 | 151 | print("") 152 | print("------------\nTest Errors\n------------") 153 | print "\t%0.2f in change" % r.take_order('Kale Salad', 5.00) 154 | print "\t%0.2f in change" % r.take_order('ShackBurger', 0.25) 155 | print "\t%0.2f in change" % r.take_big_order(('ShackBurger', 'Kale Salad'), 5.00) 156 | print "\t%0.2f in change" % r.take_big_order(('ShackBurger', 'Fries'), 5.00) 157 | -------------------------------------------------------------------------------- /lesson-6/slides.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LindsayYoung/python-class/63821805dab826ab4c8b030c3cbdd6835435a3ce/lesson-6/slides.pdf -------------------------------------------------------------------------------- /lesson-7/find_member.py: -------------------------------------------------------------------------------- 1 | # you need an api key to run this program http://sunlightfoundation.com/api/accounts/register/ 2 | 3 | import json 4 | # install this later 5 | import requests 6 | 7 | apikey = # get your own at http://sunlightfoundation.com/api/accounts/register/ 8 | 9 | # Here is an example of the last part of the url we are trying to build. 10 | # /legislators/locate?zip=11216 11 | 12 | endpoint = 'https://congress.api.sunlightfoundation.com/legislators/locate' 13 | 14 | zip = raw_input("give me a zipcode: ") 15 | 16 | query_params = {'zip': zip, 'apikey': apikey} 17 | 18 | response = requests.get(endpoint, params=query_params) 19 | 20 | print(response.url) 21 | 22 | data = response.json() 23 | 24 | for result in data['results']: 25 | name = result['title'] + " " + result['last_name'] 26 | print name 27 | -------------------------------------------------------------------------------- /lesson-7/find_member_commented.py: -------------------------------------------------------------------------------- 1 | # you need an api key to run this program http://sunlightfoundation.com/api/accounts/register/ 2 | # This prrogram will find the members of Congress that represent a given zipcode 3 | 4 | # the json module will help us use the information we get as lists and dictionaries 5 | import json 6 | # install this if you don't have it, use pip install or easy_install 7 | import requests 8 | 9 | # this lets us access Sunlight APIs 10 | apikey = # get your own at http://sunlightfoundation.com/api/accounts/register/ 11 | 12 | # We structure api calls by reading documentaion about them: 13 | # The documentation for the Congress API is at https://sunlightlabs.github.io/congress/ 14 | # We can also use Sunlight's query builder to help us understand how to format our query http://tryit.sunlightfoundation.com/congress 15 | 16 | # This is the url that we are going to use to contact the API 17 | # The legislators/locate part is the methoid we are using, we can think of it as part as telling the API what kind of information we are interested in 18 | endpoint = 'https://congress.api.sunlightfoundation.com/legislators/locate' 19 | 20 | # We started out with this hard coded but we made this something the users can decide 21 | zip = raw_input("give me a zipcode: ") 22 | 23 | # These are the arguements we want to pass in. These variables are the way we ask the API questions. 24 | query_params = {'zip': zip, 'apikey': apikey} 25 | 26 | # Here we are using the requests package to format our url for us and get the information from the website. 27 | # .get is a function in the requests package we are using. 28 | # We pass in a dictionary of variables we want after the endpoint. (Check out the Requests documentation for more informaion.) 29 | response = requests.get(endpoint, params=query_params) 30 | 31 | # The requests library makes it easy for us to check what url it is using for its request. This is great for debugging! Put this url into a browser and see your result. 32 | print(response.url) 33 | # it should look something like: 34 | # https://congress.api.sunlightfoundation.com/legislators/locate?zip=92886&apikey=your_key 35 | 36 | # We are using the json module to get the data into a format python can easily use. 37 | data = response.json() 38 | 39 | # Looping through each person in the results list that was returned from the API 40 | for result in data['results']: 41 | # for each person we are going to concatinate their title and name. Concatinate just means add strings. 42 | name = result['title'] + " " + result['last_name'] 43 | print name 44 | -------------------------------------------------------------------------------- /lesson-8/capitol_words.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import csv 3 | 4 | url = raw_input("give me the capitolwords text endpoint you want to make into a spreadsheet") 5 | 6 | response = requests.get(url).json() 7 | 8 | with open("Reid_weekend.csv", "wb") as csvfile: 9 | writer = csv.writer(csvfile) 10 | writer.writerow(['speaker', 'state', 'capitolwords_url', 'speach', 'origin_url', 'title']) 11 | 12 | for n in response['results']: 13 | speaker = n['speaker_first'] + " " + n['speaker_last'] 14 | state = n['speaker_state'] 15 | capitolwords_url = n['capitolwords_url'] 16 | speach = n['speaking'][0] 17 | origin_url = n['origin_url'] 18 | title = n['title'] 19 | writer.writerow([speaker, state, capitolwords_url, speach, origin_url, title]) 20 | --------------------------------------------------------------------------------