├── section_07_(files) ├── class-stats.csv ├── contacts.csv ├── survey.csv ├── states_enumerate.py ├── all_employees.csv ├── read_text.py ├── states.txt ├── states.csv ├── read_csv.csv ├── state_info.csv ├── write_population.py ├── with_open.py ├── read_csv.py └── states_pop.txt ├── section_09_(functions) ├── lessons.txt ├── textfile_to_string.py ├── division.py ├── happy_hour_attendees.txt ├── events.csv ├── film_screening_attendees.txt ├── open_csvfile.py ├── csv_to_dict.py ├── remove_duplicates.py └── dropdown_states.py ├── section_05_(loops) ├── movies.csv ├── calendar.py ├── enumerate.py ├── while_menu.py ├── loops_gif.py ├── loops.py ├── for_quadrants.py ├── zip_bingo.py ├── while_quadrants.py ├── states.html └── 12days.py ├── section_14_(exceptions) ├── exceptions_01.py ├── exceptions_02.py ├── exceptions_07.py ├── exceptions_08.py ├── multiple_exceptions.py ├── exceptions_06.py ├── exceptions_05.py ├── exceptions_03.py └── exceptions_04.py ├── playtime ├── lesson04_csvtolist.py ├── lesson04_deduplicate.py ├── lesson02_fibonnaci.py ├── lesson01_twitter.py ├── lesson02_pbj_while.py ├── lesson04_group_csvtodict.py ├── lesson03_states.py ├── lesson03_compare.py ├── lesson03_contacts.py ├── lesson02_states.py ├── lesson02_movies.py ├── lesson05_firstapi.py ├── lesson02_fizzbuzz.py ├── lesson01_pbj.py └── lesson02_99bottles.py ├── section_15_(intermediate) ├── quadrant.py └── timestamp.py ├── section_03_(conditionals) ├── happy_hour.py ├── volunteer_recruitment.py └── life.py ├── section_04_(lists) ├── list_deduplicate.py └── list_basics.py ├── section_10_(dictionaries) ├── dict_values.py ├── dict_get.py ├── dict_keys.py ├── dict_exercise_2.py ├── dict_items.py ├── dict_exercise.py ├── dict_update.py ├── nested_access.py └── dict_access.py ├── section_06_(str-list) ├── split.py ├── quadrants_exercise.py └── join.py ├── section_11_(api) ├── json_to_dict.py ├── contacts.json ├── dict_to_json.py ├── using_requests.py └── dicts_and_lists.py ├── contacts.json ├── section_01_(basics) ├── simple_math.py ├── data_types.py ├── basic_syntax.py └── variable_assignment.py ├── LICENSE ├── section_02_(strings) ├── string_lower.py ├── is_alphaspace.py ├── string_find.py ├── string_count.py ├── string_replace.py ├── string_format.py └── slicing.py ├── knowledge_share └── lesson05_apis.py ├── installing_pip.md ├── start-here.md ├── .gitignore └── README.md /section_07_(files)/class-stats.csv: -------------------------------------------------------------------------------- 1 | Class,Date,Attendees 2 | Lesson 1,February 24,44 3 | Lesson 2,February 24,23 4 | Lesson 3,February 24,12 -------------------------------------------------------------------------------- /section_09_(functions)/lessons.txt: -------------------------------------------------------------------------------- 1 | Lesson 1: Strings and Conditionals 2 | Lesson 2: Lists and Loops 3 | Lesson 3: Dictionaries and File Handling -------------------------------------------------------------------------------- /section_05_(loops)/movies.csv: -------------------------------------------------------------------------------- 1 | Title, Rating, Bechdel, IMDB, Genre 2 | Jurassic Park, PG-13, 3, 8.0, Adventure / Sci-Fi 3 | Back to the Future, PG, 1, 8.5, Adventure / Comedy / Sci-Fi -------------------------------------------------------------------------------- /section_09_(functions)/textfile_to_string.py: -------------------------------------------------------------------------------- 1 | def textfile_to_string(filename): 2 | 3 | with open(filename, "r") as text_file: 4 | text = text_file.read() 5 | 6 | return text -------------------------------------------------------------------------------- /section_07_(files)/contacts.csv: -------------------------------------------------------------------------------- 1 | Name,Phone,Github,Twitter 2 | Shannon,202-555-1234,@shannonturner,@svt827 3 | Beyonce,303-404-9876,@bey,@beyonce 4 | Tegan and Sara,301-777-3313,@heartthrob,@teganandsara -------------------------------------------------------------------------------- /section_14_(exceptions)/exceptions_01.py: -------------------------------------------------------------------------------- 1 | # Example #1: Simple Exception handling 2 | 3 | try: 4 | print 1/0 # This will fail. 5 | except ZeroDivisionError: 6 | print "You can't divide by zero!" 7 | -------------------------------------------------------------------------------- /section_07_(files)/survey.csv: -------------------------------------------------------------------------------- 1 | email, twitter, github 2 | shannon@ijustworkhe.re,@svt827,@shannonturner 3 | beyonce@beyonce.com,@beyonce,@bey 4 | pb@candykingd.om,@pbg,@bubblegum 5 | rachel@maddow.com,@maddow,@maddowshow -------------------------------------------------------------------------------- /playtime/lesson04_csvtolist.py: -------------------------------------------------------------------------------- 1 | # Challenge level: Beginner 2 | 3 | # Goal: Using the code from Lesson 3: File handling and dictionaries, create a function that will open a CSV file and return the result as a nested list. -------------------------------------------------------------------------------- /section_15_(intermediate)/quadrant.py: -------------------------------------------------------------------------------- 1 | def quadrant(address): 2 | 3 | "Returns the DC quadrant for the address given" 4 | 5 | return [quadrant for quadrant in address.split(' ') if quadrant in ['NW', 'NE', 'SW', 'SE']] or None 6 | -------------------------------------------------------------------------------- /section_09_(functions)/division.py: -------------------------------------------------------------------------------- 1 | def division(x, y): 2 | if y == 0: 3 | return # You can't divide by Zero! If you do, you'll get an error. 4 | return x/y # It's implied that this only happens when y != 0, since otherwise the function would have ended at line 3 -------------------------------------------------------------------------------- /section_09_(functions)/happy_hour_attendees.txt: -------------------------------------------------------------------------------- 1 | lia@email.add 2 | maite@email.add 3 | nikki@email.add 4 | jane@email.add 5 | samira@email.add 6 | shelley@email.add 7 | tina@email.add 8 | linda@email.add 9 | aubra@email.add 10 | susanna@email.add 11 | fiona@email.add 12 | madeline@email.add -------------------------------------------------------------------------------- /section_09_(functions)/events.csv: -------------------------------------------------------------------------------- 1 | date,description,location,attendees,cost,notes 2 | 1/11/2014,Film Screening,In-office,12,$10 suggested,Panel afterwards 3 | 2/22/2014,Happy Hour,That bar with the drinks,12,0,Too loud 4 | 3/31/2014,Panel Discussion,Partner Organization,200,0,Full capacity and 30 on waitlist -------------------------------------------------------------------------------- /section_09_(functions)/film_screening_attendees.txt: -------------------------------------------------------------------------------- 1 | robin@email.add 2 | taylor@email.add 3 | emily@email.add 4 | nikki@email.add 5 | rebecca@email.add 6 | jane@email.add 7 | sophia@email.add 8 | shelley@email.add 9 | jennifer@email.add 10 | aubra@email.add 11 | kate@email.add 12 | madeline@email.add -------------------------------------------------------------------------------- /section_09_(functions)/open_csvfile.py: -------------------------------------------------------------------------------- 1 | def open_csvfile(filename, delimiter=','): 2 | 3 | with open(filename, "r") as csv_file: 4 | rows = csv_file.read().split("\n") 5 | 6 | for index, row in enumerate(rows): 7 | rows[index] = row.split(delimiter) 8 | 9 | return rows -------------------------------------------------------------------------------- /section_07_(files)/states_enumerate.py: -------------------------------------------------------------------------------- 1 | with open("states.csv", "r") as states_file: 2 | states = states_file.read().split("\n") 3 | 4 | for index, state in enumerate(states): 5 | states[index] = states[index].split(",") 6 | 7 | print "{0}'s abbreviation is {1}".format(states[index][1], states[index][0]) 8 | 9 | # print states 10 | -------------------------------------------------------------------------------- /section_03_(conditionals)/happy_hour.py: -------------------------------------------------------------------------------- 1 | # Happy Hour! 2 | # Change the age to change the behavior of this program 3 | 4 | age = 30 5 | 6 | if age >= 21: 7 | print "I would like a three philosophers, please" 8 | elif age >= 18: # If age is less than 21 but greater than or equal to 18 9 | print "I'm here to vote -- you can vote at bars, right?" 10 | else: 11 | print "I really shouldn't even be here but can I have a cherry coke please?" -------------------------------------------------------------------------------- /section_14_(exceptions)/exceptions_02.py: -------------------------------------------------------------------------------- 1 | # Example #2: Exceptions trigger the except block and skip any code after the error. 2 | 3 | try: 4 | print 1/0 # This will fail. 5 | print "I'm code that will never run!" 6 | 7 | print 555/0 # This *would* fail, except we never get here. That's why it's best to use a try block on the fewest lines of code possible. 8 | 9 | except ZeroDivisionError: 10 | print "You still can't divide by zero!" 11 | -------------------------------------------------------------------------------- /section_14_(exceptions)/exceptions_07.py: -------------------------------------------------------------------------------- 1 | # Example #7: try-else 2 | 3 | # Use an else block attached to a try block when you want to execute code only when no errors occured. 4 | 5 | user_input = raw_input("Please enter a number: ") 6 | 7 | try: 8 | user_input = int(float(user_input)) 9 | except ValueError: 10 | print "You didn't enter a number, did you?" 11 | 12 | else: # no errors occurred 13 | print "Hooray! We didn't encounter any errors!" 14 | print "Oh, by the way, your number was: {0}".format(user_input) 15 | -------------------------------------------------------------------------------- /section_09_(functions)/csv_to_dict.py: -------------------------------------------------------------------------------- 1 | 2 | def csvtodict(filename): 3 | 4 | with open(filename, 'r') as csv_file: 5 | text = csv_file.read().strip().split('\n') 6 | 7 | header_row = text[0].split(',') 8 | 9 | dictionary = {} 10 | 11 | for row, line in enumerate(text[1:]): 12 | 13 | dictionary[row] = {} 14 | 15 | for col, cell in enumerate(line.split(',')): 16 | 17 | dictionary[row][header_row[col]] = cell 18 | 19 | 20 | return dictionary 21 | 22 | 23 | print csvtodict('events.csv') 24 | -------------------------------------------------------------------------------- /section_09_(functions)/remove_duplicates.py: -------------------------------------------------------------------------------- 1 | def remove_duplicates(from_list): 2 | 3 | """ 4 | The function list() will convert an item to a list. 5 | The function set() will convert an item to a set. 6 | 7 | A set is similar to a list, but all values must be unique. 8 | 9 | Converting a list to a set removes all duplicate values. 10 | We then convert it back to a list since we're most comfortable working with lists. 11 | 12 | """ 13 | 14 | from_list = list(set(from_list)) 15 | 16 | return from_list 17 | 18 | 19 | -------------------------------------------------------------------------------- /section_07_(files)/all_employees.csv: -------------------------------------------------------------------------------- 1 | name, email, phone, department, position 2 | Shannon, shannon@ijustworkhe.re, 202-555-1234, Tech, Software Developer 3 | Beyonce, beyonce@beyonce.com, 303-404-9876, Communications, Star 4 | Ice King, iceking@adventureti.me, 210-555-8655, Frozen Affairs, Lead Sorcerer 5 | Bender, bender@benderisgre.at, 310-555-9292, Manufacturing, Bender 6 | Princess Bubblegum, pb@candykingd.om, 410-555-2121, Candy Kingdom, Princess 7 | Lumpy Space Princess, lumps@lsp.net, 530-555-3090, Lumpy Space, Lumpification Specialist 8 | Rachel Maddow, rachel@maddow.com, 602-555-1212, News, Newscaster -------------------------------------------------------------------------------- /section_07_(files)/read_text.py: -------------------------------------------------------------------------------- 1 | # If you're new to file handling, be sure to check out with_open.py first! 2 | 3 | with open('states.txt', 'r') as states_file: 4 | states = states_file.read().split("\n") 5 | 6 | print states 7 | 8 | # .read() is a file method that reads the file (which file? the one in the file object just before the dot) and returns the whole contents as a string. 9 | 10 | # Instead of leaving it as a string, we're splitting the file into a list at every new line, and we save that list into the variable states 11 | 12 | # Now we can loop over that list! 13 | 14 | for state in states: 15 | print state -------------------------------------------------------------------------------- /section_03_(conditionals)/volunteer_recruitment.py: -------------------------------------------------------------------------------- 1 | # Volunteer recruitment 2 | # Change these variables to change the behavior of your program 3 | volunteers_goal = 20 4 | current_volunteers = 100 5 | 6 | # Is current_volunteers less than, equal to, or greater than volunteers_goal? 7 | 8 | if current_volunteers < volunteers_goal: 9 | print "You still have {0} volunteers to recruit!".format(volunteers_goal - current_volunteers) 10 | elif current_volunteers == volunteers_goal: 11 | print "You met your goal exactly! Way to go!" 12 | elif current_volunteers > volunteers_goal: 13 | print "You exceeded your recruitment goals by {0}! Way to go!".format(current_volunteers - volunteers_goal) -------------------------------------------------------------------------------- /section_14_(exceptions)/exceptions_08.py: -------------------------------------------------------------------------------- 1 | # Example #8: try-finally 2 | 3 | # Use an finally block attached to a try block to execute code no matter what happens 4 | 5 | user_input = raw_input("Please enter a number: ") 6 | 7 | try: 8 | user_input = int(float(user_input)) 9 | 10 | except ValueError: 11 | print "You didn't enter a number, did you?" 12 | 13 | else: # no errors occurred 14 | print "Hooray! We didn't encounter any errors!" 15 | 16 | finally: # no matter what 17 | print "Here was your input: {0}".format(user_input) 18 | 19 | print "'finally' isn't that common though, and you could really just put your code outside of the block entirely." 20 | print "Here was your input: {0}".format(user_input) # Like this! 21 | -------------------------------------------------------------------------------- /section_04_(lists)/list_deduplicate.py: -------------------------------------------------------------------------------- 1 | # De-duplicating a list 2 | 3 | # De-duplicating list is one of the most commonly used actions in computer programming 4 | 5 | # Here, we have a list of state abbreviations ... but our list has lots of duplicates! 6 | list_with_duplicates = ['CT', 'DE', 'MN', 'OH', 'CT', 'OK', 'MT', 'FL', 'TX', 'CT', 'OK', 'TX', 'PA', 'OK'] 7 | 8 | # First we convert our list with duplicates to the set type, which will eliminate the duplicates 9 | # Next we convert that set back to a list so we can use it as intended. 10 | list_without_duplicates = list(set(list_with_duplicates)) 11 | 12 | print "List with duplicates: {0}".format(list_with_duplicates) 13 | 14 | print "List without duplicates: {0}".format(list_without_duplicates) -------------------------------------------------------------------------------- /section_07_(files)/states.txt: -------------------------------------------------------------------------------- 1 | Alabama 2 | Alaska 3 | Arizona 4 | Arkansas 5 | California 6 | Colorado 7 | Connecticut 8 | Delaware 9 | District Of Columbia 10 | Florida 11 | Georgia 12 | Hawaii 13 | Idaho 14 | Illinois 15 | Indiana 16 | Iowa 17 | Kansas 18 | Kentucky 19 | Louisiana 20 | Maine 21 | Maryland 22 | Massachusetts 23 | Michigan 24 | Minnesota 25 | Mississippi 26 | Missouri 27 | Montana 28 | Nebraska 29 | Nevada 30 | New Hampshire 31 | New Jersey 32 | New Mexico 33 | New York 34 | North Carolina 35 | North Dakota 36 | Ohio 37 | Oklahoma 38 | Oregon 39 | Pennsylvania 40 | Rhode Island 41 | South Carolina 42 | South Dakota 43 | Tennessee 44 | Texas 45 | Utah 46 | Vermont 47 | Virginia 48 | Washington 49 | West Virginia 50 | Wisconsin 51 | Wyoming -------------------------------------------------------------------------------- /playtime/lesson04_deduplicate.py: -------------------------------------------------------------------------------- 1 | # Challenge level: Beginner 2 | 3 | # Scenario: You have two files containing a list of email addresses of people who attended your events. 4 | # File 1: People who attended your Film Screening event 5 | # https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/film_screening_attendees.txt 6 | # 7 | # File 2: People who attended your Happy hour 8 | # https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/happy_hour_attendees.txt 9 | # 10 | 11 | # Note: You should create functions to accomplish your goals. 12 | 13 | # Goal 1: You want to get a de-duplicated list of all of the people who have come to your events. 14 | 15 | # Goal 2: Who came to *both* your Film Screening and your Happy hour? 16 | -------------------------------------------------------------------------------- /section_14_(exceptions)/multiple_exceptions.py: -------------------------------------------------------------------------------- 1 | # You can also handle multiple types of exceptions in the same block 2 | 3 | # In the example below, changing age at line five will change the behavior of the program. 4 | # If age can be converted to an int, line 13 will run. 5 | # If age is a string, but cannot be converted to an int, a ValueError will occur 6 | # If age is a different type of thing (a dictionary, list, etc), 7 | # a TypeError will occur since those cannot be converted into a list 8 | 9 | age = '' # try with 100 or with 'x100' or with ['100'] or with None or with False or with {'age': 100} 10 | 11 | try: 12 | age = int(age) 13 | except (TypeError, ValueError) as err: 14 | print "Invalid entry: {0}; error: {1}".format(age, err) 15 | else: 16 | print "Your age is: {0}".format(age) -------------------------------------------------------------------------------- /section_10_(dictionaries)/dict_values.py: -------------------------------------------------------------------------------- 1 | # If you're new to dictionaries, you might want to start with dict_access.py 2 | 3 | # We create a dictionary. 4 | 5 | contacts = { 6 | 'Shannon': '202-555-1234', 7 | 'Amy': '410-515-3000', 8 | 'Jen': '301-600-5555', 9 | 'Julie': '202-333-9876' 10 | } 11 | 12 | # We can use the dictionary method .values() to give us a list of all of the values in contacts. 13 | 14 | print contacts.values() 15 | 16 | for phone in contacts.values(): 17 | print "{0}".format(phone) 18 | 19 | # .values() is used less frequently than .keys() since you can't get the key from the value (but you can get the value if you know the key) 20 | 21 | # Use .values() when you don't care what the key is, you just want a list of all of the values. It's less common, but still good to know. -------------------------------------------------------------------------------- /playtime/lesson02_fibonnaci.py: -------------------------------------------------------------------------------- 1 | # Fibonnaci Sequence 2 | 3 | # Difficulty: Advanced 4 | 5 | # NOTE: This is *not* a practical example of how you'll use coding in your day to day, BUT it does appear on a surprising number of in-person coding interviews. Why employers rely on something so impractical to gauge your coding ability is beyond me. 6 | # But since they're using it, maybe in this narrow sense it's a practical exercise to know how to do after all. 7 | 8 | 9 | # The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it. 10 | 11 | # Create a program that will generate the first 10 numbers in the Fibonacci Sequence. 12 | 13 | # When completed, your program should have the output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 14 | -------------------------------------------------------------------------------- /section_14_(exceptions)/exceptions_06.py: -------------------------------------------------------------------------------- 1 | # Example #6: raise (no arguments) 2 | 3 | import time 4 | 5 | print "I'm going to count down from 1000 as fast as I can. Hit Ctrl+C three times to stop." 6 | 7 | x = 1000 8 | times_paused = 0 9 | 10 | while x > 0: 11 | 12 | try: 13 | print x 14 | x-=1 15 | except KeyboardInterrupt: 16 | 17 | times_paused += 1 18 | 19 | print " You have paused {0} time(s).".format(times_paused) 20 | 21 | if times_paused == 3: 22 | print "You paused 3 times. Ending early by raising the original exception (KeyboardInterrupt)" 23 | raise # this will raise the *original* exception, which in this case is KeyboardInterrupt 24 | 25 | print "Pausing for {0} seconds.".format(times_paused) 26 | time.sleep(times_paused) 27 | -------------------------------------------------------------------------------- /section_06_(str-list)/split.py: -------------------------------------------------------------------------------- 1 | address = "1600 Pennsylvania Ave NW Washington, DC" 2 | 3 | # .split() is a string method (a function that works only on strings) that splits a string into a list based on some delimiter. 4 | # In this example, we're splitting address into a list at every space. 5 | address = address.split(" ") 6 | 7 | # Address is now a list equal to: 8 | # ['1600', 'Pennsylvania', 'Ave', 'NW', 'Washington,', 'DC'] 9 | # Note that the list created is a list of strings. 10 | 11 | # And since it's a list, you can loop over it! 12 | 13 | # .split() is commonly used to split text files into a list (at each newline) 14 | # .split() is also commonly used to split spreadsheet files in comma separated value (CSV) format into a list (at each comma) 15 | 16 | # Any time you need to split a string into multiple parts, you can use .split() -------------------------------------------------------------------------------- /section_05_(loops)/calendar.py: -------------------------------------------------------------------------------- 1 | months_in_year = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] 2 | 3 | days_of_week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] 4 | 5 | # Note how in line 6 we slice on the list we are looping over instead of looping over the entire list of months. 6 | for month in months_in_year[0:6]: # For each month in the first six months ... 7 | print "\n" 8 | print month 9 | print "\n" 10 | 11 | for week in range(1, 5): 12 | print "Week {0}".format(week) 13 | 14 | # Notice that we're slicing again in line 15 instead of looping over the entire week. 15 | for day in days_of_week[-2:]: # For the last two days of the week (Saturday and Sunday) 16 | print day 17 | 18 | # By removing the slicing from lines 6 and 15, we get the full year (or at least 12 months with 4 weeks of 7 days) -------------------------------------------------------------------------------- /section_05_(loops)/enumerate.py: -------------------------------------------------------------------------------- 1 | # enumerate() example 2 | 3 | # enumerate() is used to loop through a list, and for each item in that list, to also give the index where that item can be found 4 | 5 | days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] 6 | 7 | # This is how we're used to looping -- for each item in this list, print this item 8 | for day in days: 9 | print day 10 | 11 | 12 | # Now we add a layer of complexity. Notice how two variables (index, day) are being created by the for loop. 13 | for index, day in enumerate(days): 14 | print "days[{0}] contains {1}".format(index, day) 15 | print "day contains {0}".format(day) 16 | 17 | 18 | # Since we humans aren't counting days by zero, we do a little addition inside the .format() 19 | for index, day in enumerate(days): 20 | print "{0} is day # {1}".format(day, index+1) -------------------------------------------------------------------------------- /section_11_(api)/json_to_dict.py: -------------------------------------------------------------------------------- 1 | # Converting Dictionaries (and lists and strings, etc) to JSON 2 | 3 | # First, use the built-in library json. You don't need to pip install this, it comes with python. 4 | import json 5 | 6 | # Now, load the file (contacts.json) that you created in https://github.com/shannonturner/python-lessons/blob/master/section_11_(api)/dict_to_json.py 7 | with open('contacts.json', 'r') as contacts_file: 8 | contacts = contacts_file.read() 9 | 10 | print contacts 11 | 12 | print "\n\n contacts above is a string" 13 | 14 | # Now we have loaded the contents of the file as a string that looks like JSON. 15 | # json.loads() will allow us to load it back into a form Python can use (and loop over) 16 | contacts = json.loads(contacts) 17 | 18 | print contacts 19 | 20 | print "\n\n now you can loop over contacts, since it is a list (with dictionaries and other goodies nested within)" -------------------------------------------------------------------------------- /contacts.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "enemies": [], 4 | "friends": [ 5 | { 6 | "Shannon": { 7 | "github": "@shannonturner", 8 | "phone": "202-555-1234", 9 | "twitter": "@svt827" 10 | } 11 | }, 12 | { 13 | "Amy": { 14 | "email": "amy@amy.org", 15 | "fax": "410-555-3001", 16 | "phone": "410-515-3000" 17 | } 18 | }, 19 | { 20 | "Jen": { 21 | "email": "jen@jen.biz", 22 | "phone": "301-600-5555" 23 | } 24 | }, 25 | { 26 | "Julie": { 27 | "phone": "202-333-9876" 28 | } 29 | } 30 | ] 31 | } 32 | ] -------------------------------------------------------------------------------- /section_11_(api)/contacts.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "enemies": [], 4 | "friends": [ 5 | { 6 | "Shannon": { 7 | "github": "@shannonturner", 8 | "phone": "202-555-1234", 9 | "twitter": "@svt827" 10 | } 11 | }, 12 | { 13 | "Amy": { 14 | "email": "amy@amy.org", 15 | "fax": "410-555-3001", 16 | "phone": "410-515-3000" 17 | } 18 | }, 19 | { 20 | "Jen": { 21 | "email": "jen@jen.biz", 22 | "phone": "301-600-5555" 23 | } 24 | }, 25 | { 26 | "Julie": { 27 | "phone": "202-333-9876" 28 | } 29 | } 30 | ] 31 | } 32 | ] -------------------------------------------------------------------------------- /section_07_(files)/states.csv: -------------------------------------------------------------------------------- 1 | AL,Alabama 2 | AK,Alaska 3 | AZ,Arizona 4 | AR,Arkansas 5 | CA,California 6 | CO,Colorado 7 | CT,Connecticut 8 | DE,Delaware 9 | DC,District Of Columbia 10 | FL,Florida 11 | GA,Georgia 12 | HI,Hawaii 13 | ID,Idaho 14 | IL,Illinois 15 | IN,Indiana 16 | IA,Iowa 17 | KS,Kansas 18 | KY,Kentucky 19 | LA,Louisiana 20 | ME,Maine 21 | MD,Maryland 22 | MA,Massachusetts 23 | MI,Michigan 24 | MN,Minnesota 25 | MS,Mississippi 26 | MO,Missouri 27 | MT,Montana 28 | NE,Nebraska 29 | NV,Nevada 30 | NH,New Hampshire 31 | NJ,New Jersey 32 | NM,New Mexico 33 | NY,New York 34 | NC,North Carolina 35 | ND,North Dakota 36 | OH,Ohio 37 | OK,Oklahoma 38 | OR,Oregon 39 | PW,PALAU 40 | PA,Pennsylvania 41 | PR,PUERTO RICO 42 | RI,Rhode Island 43 | SC,South Carolina 44 | SD,South Dakota 45 | TN,Tennessee 46 | TX,Texas 47 | UT,Utah 48 | VT,Vermont 49 | VA,Virginia 50 | WA,Washington 51 | WV,West Virginia 52 | WI,Wisconsin 53 | WY,Wyoming -------------------------------------------------------------------------------- /section_14_(exceptions)/exceptions_05.py: -------------------------------------------------------------------------------- 1 | # Example #5: Nesting exception handling 2 | 3 | # Exception handling works the same as any other indentation level in Python 4 | 5 | user_input = raw_input(" Example #5: enter a number: ") 6 | 7 | try: 8 | user_input = int(user_input) 9 | except ValueError: 10 | try: 11 | print "User input was either a float or a string." 12 | user_input = int(float(user_input)) 13 | print "Turns out it was a float! {0}".format(user_input) 14 | except ValueError: 15 | print "Guess {0} was a string and not a number at all.".format(user_input) 16 | 17 | print "Now the code block above works pretty much the same as the following: " 18 | 19 | user_input = raw_input(" Example #5: enter a number: ") 20 | 21 | try: 22 | user_input = int(float(user_input)) 23 | except ValueError: 24 | print "Guess {0} was a string and not a number at all.".format(user_input) 25 | -------------------------------------------------------------------------------- /playtime/lesson01_twitter.py: -------------------------------------------------------------------------------- 1 | # Difficulty Level: Beginner 2 | # Exercise: Tweet length calculator 3 | 4 | # Part one: 5 | # Create a variable called tweet and put some text in it 6 | # maybe something like "Hear Me Code class was so much fun today!" 7 | 8 | # Measure the length of that tweet. 9 | 10 | # Was that tweet more than 140 characters? 11 | # If so, tell the user it was too long! 12 | # Was that tweet 140 or fewer characters? 13 | # If so, tell the user how witty they are! 14 | 15 | 16 | # Part two: 17 | # Adjust the program to say how many characters you have remaining to use, or how many you need to trim by in order to meet the 140 character limit 18 | 19 | 20 | # Part three: 21 | # Twitter announced they are changing their character limit to 280, but they might change it again. 22 | # Can you make your code flexible enough so that you don't have to replace the character limit in multiple places in your code? 23 | 24 | -------------------------------------------------------------------------------- /section_10_(dictionaries)/dict_get.py: -------------------------------------------------------------------------------- 1 | # If you're new to dictionaries, you might want to start with dict_access.py 2 | 3 | # We create a dictionary. 4 | 5 | contacts = { 6 | 'Shannon': '202-555-1234', 7 | 'Amy': '410-515-3000', 8 | 'Jen': '301-600-5555', 9 | 'Julie': '202-333-9876' 10 | } 11 | 12 | name = raw_input("Enter the name of the person whose phone number you want: ") 13 | 14 | print "We will get a KeyError if you entered a name that wasn't in the dictionary." 15 | print "{0}'s number is: {1}".format(name, contacts[name]) 16 | 17 | print "But there's a way we don't need to worry about KeyErrors." 18 | 19 | name = raw_input("Enter the name of the person whose phone number you want ... might I suggest Frankenstein? ") 20 | 21 | # .get() is a dictionary method that lets us safely access a dictionary even if that key doesn't exist. 22 | 23 | print "{0}'s number is ... {1}".format(name, contacts.get(name, " ... I couldn't find it!")) -------------------------------------------------------------------------------- /section_14_(exceptions)/exceptions_03.py: -------------------------------------------------------------------------------- 1 | # Example #3: Different types of exceptions can be caught. 2 | 3 | print "Example #3: Phonebook!" 4 | 5 | phonebook = {} 6 | 7 | while True: # this will loop forever until we issue a break! 8 | 9 | key = raw_input(" (Ex #3, Phonebook) Please enter a person's name, or leave blank to quit: ") 10 | 11 | if key == '': 12 | break 13 | 14 | value = raw_input(" (Ex #3, Phonebook) Please enter {0}'s phone number with no punctuation: ") 15 | 16 | phonebook[key] = value 17 | 18 | 19 | user_input = raw_input(" Okay, now we're done entering names. Please enter the name of the person whose number you would like: ") 20 | 21 | try: 22 | print int(phonebook[user_input]) 23 | except KeyError: 24 | print "You don't have {0}'s phone number!".format(user_input) 25 | except ValueError: 26 | print "You typed in punctuation, didn't you?" 27 | print "Here's the number anyway ... {0}".format(phonebook[user_input]) 28 | -------------------------------------------------------------------------------- /section_05_(loops)/while_menu.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | instructions = """Type a one-letter command and hit enter: 4 | A to add a name to your list 5 | R to remove a name from your list 6 | S to show the names in your list 7 | Q to quit 8 | >""" 9 | 10 | allowed_commands = ['a', 'r', 's', 'q'] 11 | names = [] 12 | 13 | command = raw_input(instructions) 14 | 15 | while command.lower() in allowed_commands: 16 | 17 | if command.lower() == 'a': 18 | name = raw_input("Enter a name to add to your list: ") 19 | names.append(name) 20 | elif command.lower() == 'r': 21 | name = raw_input("Enter a name to remove from your list: ") 22 | names.pop(names.index(name)) # this will remove the first instance of this name that appears; if there are duplicates, only the first one will be removed 23 | elif command.lower() == 's': 24 | print '\n'.join(names) 25 | elif command.lower() == 'q': 26 | break # this will break out of the while loop 27 | 28 | command = raw_input(instructions) -------------------------------------------------------------------------------- /section_10_(dictionaries)/dict_keys.py: -------------------------------------------------------------------------------- 1 | # If you're new to dictionaries, you might want to start with dict_access.py 2 | 3 | # We create a dictionary. 4 | 5 | contacts = { 6 | 'Shannon': '202-555-1234', 7 | 'Amy': '410-515-3000', 8 | 'Jen': '301-600-5555', 9 | 'Julie': '202-333-9876' 10 | } 11 | 12 | # We can use the dictionary method .keys() to give us a list of all of the keys in contacts. 13 | 14 | print contacts.keys() 15 | 16 | for contact in contacts.keys(): 17 | print "{0}'s number is {1}".format(contact, contacts[contact]) 18 | 19 | # Dictionaries are unordered, so the keys (and their values) might be in a different order each time. Or they might not. Either way, that's normal. 20 | 21 | # In other words, you can't rely on the ordering of anything in a dictionary. But you could apply ordering to the keys. 22 | 23 | # The built-in function sorted() will sort a list in ascending order. 24 | 25 | for contact in sorted(contacts.keys()): 26 | print "{0}'s number is {1}".format(contact, contacts[contact]) -------------------------------------------------------------------------------- /section_01_(basics)/simple_math.py: -------------------------------------------------------------------------------- 1 | 2 | # Simple Math 3 | 4 | # We're going to work with print statements to output the results to the screen. 5 | 6 | # You can separate multiple print items with a comma, as shown below: 7 | 8 | print "Four times four is ", 4 * 4 9 | 10 | # Addition 11 | print "5 + 3 is ", 5 + 3 12 | 13 | # Subtraction 14 | print "6 - 2 is ", 6 - 2 15 | 16 | # Multiplication 17 | print "10 * 20 is ", 10 * 20 18 | 19 | # Division 20 | print "55 / 2 is ", 55 / 2 # Hmm ... ! 21 | 22 | print "By default, Python treats numbers as whole numbers (integers)" 23 | print "So in a way, Python's answer of 55 / 2 = 27 makes sense, even if it's not quite what we're looking for." 24 | print "Luckily, there are other ways to get the answer we want." 25 | 26 | # Precise Division (using floats) 27 | print "55.0 / 2 is ", 55.0 / 2 28 | print "55 / 2.0 is ", 55 / 2.0 29 | print "55.0 / 2.0 is ", 55.0 / 2.0 30 | 31 | # Remainder Division 32 | print "55 % 2 is ", 55 % 2 # This is super useful for determining whether a number is odd or even 33 | 34 | # Powers 35 | print "2 ** 10 is ", 2 ** 10 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013-2014 Shannon Turner 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so, 8 | subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 15 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 16 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 17 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 18 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | -------------------------------------------------------------------------------- /playtime/lesson02_pbj_while.py: -------------------------------------------------------------------------------- 1 | # Difficulty level: Beginner 2 | 3 | # Goal #1: Write a new version of the PB&J program that uses a while loop. Print "Making sandwich #" and the number of the sandwich until you are out of bread, peanut butter, or jelly. 4 | 5 | # Example: 6 | # bread = 4 7 | # peanut_butter = 3 8 | # jelly = 10 9 | 10 | # Output: 11 | # Making sandwich #1 12 | # Making sandwich #2 13 | # All done; only had enough bread for 2 sandwiches. 14 | 15 | # Goal #2: Modify that program to say how many sandwiches-worth of each ingredient remains. 16 | 17 | # Example 2: 18 | # bread = 10 19 | # peanut_butter = 10 20 | # jelly = 4 21 | 22 | # Output: 23 | # Making sandwich #1 24 | # I have enough bread for 4 more sandwiches, enough peanut butter for 9 more, and enough jelly for 3 more. 25 | # Making sandwich #2 26 | # I have enough bread for 3 more sandwiches, enough peanut butter for 8 more, and enough jelly for 2 more. 27 | # Making sandwich #3 28 | # I have enough bread for 2 more sandwiches, enough peanut butter for 7 more, and enough jelly for 1 more. 29 | # Making sandwich #4 30 | # All done; I ran out of jelly. 31 | -------------------------------------------------------------------------------- /section_02_(strings)/string_lower.py: -------------------------------------------------------------------------------- 1 | # String methods: string.lower() 2 | 3 | # string.lower() is used for turning all characters in your string lowercase. 4 | # There are some related string methods too, like string.upper() 5 | 6 | name = "SHANNON!!" 7 | 8 | print name.lower() # shannon!! 9 | print name # it's back to the original of SHANNON!! 10 | 11 | # To make the changes stick: 12 | name = name.lower() 13 | 14 | print name # shannon!! 15 | 16 | 17 | # string.upper() will turn all characters in your string uppercase but otherwise works in the same manner as string.lower() 18 | 19 | greeting = "hello, hi" # not very exuberant ... 20 | 21 | print greeting.upper() # MUCH BETTER! 22 | 23 | # Making the changes stick: 24 | greeting = greeting.upper() 25 | 26 | print greeting # HELLO, hi 27 | 28 | 29 | # string.lower() and .upper() are primarily used for testing strings in a case-insensitive manner 30 | 31 | gender = 'F' 32 | 33 | if gender.lower() == 'f': 34 | print "Hi lady!" 35 | 36 | # To accomplish the same thing without string.lower(), you would have to do: 37 | if gender == 'F' or gender == 'f': 38 | print "Hi lady!" -------------------------------------------------------------------------------- /section_10_(dictionaries)/dict_exercise_2.py: -------------------------------------------------------------------------------- 1 | contacts = { 2 | "Hear Me Code": { 3 | "twitter": "@hearmecode", 4 | "github": "https://github.com/hearmecode" 5 | }, 6 | "Shannon Turner": { 7 | "twitter": "@svthmc", 8 | "github": "https://github.com/shannonturner" 9 | }, 10 | } 11 | 12 | # How to add a new item to an existing dictionary: 13 | contacts["Aliya Rahman"] = { 14 | "twitter": "@AliyaRahman", 15 | "github": "https://github.com/aliyarahman" 16 | } 17 | 18 | # Exercise 1: Add a new dictionary item to contacts for each person at your table. 19 | # Rather than editing lines 1-10 above, add new entries to the contacts dictionary below. 20 | # Keep in mind some people may not have a twitter account, and that's okay! 21 | 22 | # Exercise 2: Loop through the contacts dictionary to display everyone's contact information. 23 | # Your output should look like this: 24 | 25 | # Hear Me Code's info: 26 | # twitter: @hearmecode 27 | # github: https://github.com/hearmecode 28 | # Shannon Turner's info: 29 | # twitter: @svthmc 30 | # github: https://github.com/shannonturner 31 | -------------------------------------------------------------------------------- /section_02_(strings)/is_alphaspace.py: -------------------------------------------------------------------------------- 1 | def is_alphaspace(string): 2 | 3 | """ 4 | Returns True if all characters in the string are spaces or letters; otherwise returns False. 5 | 6 | using str.isalpha() returns a bool on whether ALL of the characters in a string are letters 7 | using str.isspace() returns a bool on whether ALL of the characters in a string are whitespace; 8 | 9 | Although it's not a string method, this function combines the functionality of the string methods above 10 | """ 11 | 12 | return all([any([char.isspace(), char.isalpha()]) for char in string]) 13 | 14 | # This custom function will behave similarly to the str.isalpha() and str.isspace() combined together. 15 | 16 | test_string = "This string will return false for each of isalpha and isspace but it will return true for the custom function" 17 | 18 | print "test_string.isalpha() gives us: ", test_string.isalpha() 19 | print "test_string.isspace() gives us: ", test_string.isspace() 20 | 21 | # Note how the syntax differs. That's because is_alphaspace() isn't a string method, it's a custom function. 22 | print "But is_alphaspace(test_string) gives us: ", is_alphaspace(test_string) 23 | 24 | -------------------------------------------------------------------------------- /section_10_(dictionaries)/dict_items.py: -------------------------------------------------------------------------------- 1 | # If you're new to dictionaries, you might want to start with dict_access.py 2 | 3 | # We create a dictionary. 4 | 5 | contacts = { 6 | 'Shannon': '202-555-1234', 7 | 'Amy': '410-515-3000', 8 | 'Jen': '301-600-5555', 9 | 'Julie': '202-333-9876' 10 | } 11 | 12 | # We can use the dictionary method .items() to give us a list of all of the items in contacts. 13 | 14 | print contacts.items() 15 | 16 | # Strictly speaking, .items() doesn't give us a list, it gives us a *tuple*, which is another way of storing information in Python. 17 | # Tuples are almost identical to lists, except they're read-only. You can't add to/remove from a tuple. 18 | # But they're accessed and used in pretty much the same way, so we're going to treat it as if Python's giving us a list, and it will behave as we expect. 19 | 20 | # .items() gives us a key and value pair together - so we can use that directly when we're looping. 21 | 22 | for contact, phone in contacts.items(): 23 | print "{0}'s number is {1}".format(contact, phone) 24 | 25 | # .items() is probably most commonly used out of .keys(), .values(), and .items() because it gives you both the key and the value together. -------------------------------------------------------------------------------- /section_10_(dictionaries)/dict_exercise.py: -------------------------------------------------------------------------------- 1 | schools = { 2 | "geometry": { 3 | "coordinates": [ 4 | -81.50572799999999, 5 | 39.21675500000001 6 | ], 7 | "type": "Point" 8 | }, 9 | "properties": { 10 | "address": "300 Campus Drive, Parkersburg, WV 26104", 11 | "marker-color": "#3F3040", 12 | "marker-symbol": "circle", 13 | "name": "West Virginia University at Parkersburg" 14 | }, 15 | "type": "Feature" 16 | } 17 | 18 | # Example Question: How could you "slice" the dictionary to print "Feature" from line 15? 19 | # Answer: print schools["type"] 20 | 21 | # Question 1: What slice will give you a dictionary 22 | # with the key of "coordinates" and a value containing a list 23 | # with the items -81.50572799999999 and 39.21675500000001? 24 | 25 | # Question 2: What slice will give you the address of the school? 26 | 27 | # Question 3: What slice will give you the name of the school? 28 | 29 | # Question 4: What slice will give you the latitude of the school? 30 | # (Hint: the latitude is 39.216...) 31 | 32 | # Question 5 (bonus): What slice will give you the marker-color 33 | # without the hashtag in front? 34 | -------------------------------------------------------------------------------- /section_05_(loops)/loops_gif.py: -------------------------------------------------------------------------------- 1 | days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] 2 | foods_of_day = ['Manicotti', 'Tacos', 'Waffles', 'Raspberries', 'Franks', 'Salad', 'Soup'] 3 | 4 | # Example #1 5 | for day in days_of_week: 6 | print "Today is {0}".format(day) 7 | print "\n" 8 | 9 | 10 | # Example #2: Enumerate (gives the index of the list item) 11 | for (index, day) in enumerate(days_of_week): 12 | 13 | print "Today is the {0}th day of the week, which is {1}".format(index, day) # Please pardon/ignore 0th day and the grammar for "1th", "2th", "3th" 14 | 15 | # In this loop using enumerate, we can access the values of list items in two ways: directly using the looping variable day (which is preferred), or using the index. 16 | 17 | print "So day_of_week[{0}] is: {1}, which is the same as day, which is: {2}".format(index, days_of_week[index], day) 18 | print "\n" 19 | 20 | # Example #3: Zip 21 | for (day, food) in zip(days_of_week, foods_of_day): 22 | print "Today is {0} so obviously I'm having {1} for dinner.".format(day, food) 23 | 24 | # NOTE: zip relies on each list being the same length! If the lists are not the same length, zip will only loop through as many items as are in the shorter list! 25 | -------------------------------------------------------------------------------- /section_01_(basics)/data_types.py: -------------------------------------------------------------------------------- 1 | 2 | # Data types: int, float, bool, str 3 | 4 | # In Simple Math and Variable Assignment, we saw ints and floats in action. 5 | # Here's a quick refresher. 6 | 7 | # ints are whole numbers 8 | print 5 + 2, 5 - 3, 5 * 5, 5 / 2 # 7, 2, 25, 2 9 | 10 | # floats are decimal numbers 11 | print 5.4 + 2.1, 5.0 - 3, 5.7 * 5.2, 5 / 2.0 # 7.5, 2.0, 29.64, 2.5 12 | 13 | # boolean values store True or False (yes or no) 14 | print 5 > 4 # True 15 | print 3 + 3 <= 1 # False 16 | 17 | # Comparison Operators Sneak Peek 18 | # > greater than 19 | # < less than 20 | # >= greater than or equal to 21 | # <= less than or equal to 22 | # != not equal to 23 | # == is equal to 24 | 25 | # strings are covered in greater detail in Section 2 26 | # But essentially, they contain words, or really, anything you could type on a keyboard 27 | print "Yep, all those print statements you saw before? Those things between the quotes are strings! Yes, I'm a string, too. " 28 | 29 | print "Python usually isn't too strict about data types, but there are some things you can't do." 30 | 31 | # Uncomment out the next line to get an error! 32 | #print "This line here will cause an error, because you can't add strings to numbers. This is Lesson Section #" + 1 33 | 34 | -------------------------------------------------------------------------------- /section_14_(exceptions)/exceptions_04.py: -------------------------------------------------------------------------------- 1 | # Example #4: The catch-all handler: Exception 2 | 3 | print "Now we'll just repeat the try ... except block from Example #3 but with a catch-all for any exception." 4 | 5 | phonebook = {} 6 | 7 | while True: # this will loop forever until we issue a break! 8 | 9 | key = raw_input(" (Ex #3, Phonebook) Please enter a person's name, or leave blank to quit: ") 10 | 11 | if key == '': 12 | break 13 | 14 | value = raw_input(" (Ex #3, Phonebook) Please enter {0}'s phone number with no punctuation: ") 15 | 16 | phonebook[key] = value 17 | 18 | user_input = raw_input(" Okay, now we're done entering names. Please enter the name of the person whose number you would like: ") 19 | 20 | try: 21 | print int(phonebook[user_input]) 22 | except Exception, e: 23 | print "With any exception type (not just Exception), you can find out the detailed message specific to the error by using ', e' afterward." 24 | print "In this case, the detailed message was: {0}".format(e) 25 | print "Exception is best used in addition to other specific exceptions first." 26 | print "For best results, think of each except as being similar to an 'elif' statement targeting something specific; except Exception is similar to an 'else' statement being the catch-all." 27 | -------------------------------------------------------------------------------- /section_05_(loops)/loops.py: -------------------------------------------------------------------------------- 1 | 2 | def loop_example(list_to_loop_through): 3 | 4 | """ Assuming each item in list_to_loop_through is a number, return a list of each item in that list squared. """ 5 | 6 | print "I'm going to begin to loop through this list: ", list_to_loop_through, "\n" 7 | 8 | list_items_squared = [] 9 | 10 | for each_item in list_to_loop_through: 11 | 12 | print "Now I'm on: ", each_item 13 | print "{0} squared is {1}\n".format(each_item, each_item**2) 14 | 15 | list_items_squared.append(each_item**2) 16 | 17 | print "Now I'm done looping through the list, and I'm going to return the new list, where each list item has been squared." 18 | 19 | return list_items_squared 20 | 21 | 22 | ##Sample Output 23 | ## 24 | ##>>> my_list = [1, 3, 4, 5, 6, 78, 2334] 25 | ##>>> loop_example(my_list) 26 | ##I'm going to begin to loop through this list: [1, 3, 4, 5, 6, 78, 2334] 27 | ##Now I'm on: 1 28 | ##1 squared is 1 29 | ## 30 | ##Now I'm on: 3 31 | ##3 squared is 9 32 | ## 33 | ##Now I'm on: 4 34 | ##4 squared is 16 35 | ## 36 | ##Now I'm on: 5 37 | ##5 squared is 25 38 | ## 39 | ##Now I'm on: 6 40 | ##6 squared is 36 41 | ## 42 | ##Now I'm on: 78 43 | ##78 squared is 6084 44 | ## 45 | ##Now I'm on: 2334 46 | ##2334 squared is 5447556 47 | ## 48 | ##[1, 9, 16, 25, 36, 6084, 5447556] 49 | -------------------------------------------------------------------------------- /section_01_(basics)/basic_syntax.py: -------------------------------------------------------------------------------- 1 | 2 | # Basic Syntax 3 | 4 | # This is a comment. 5 | # That means Python will let you write notes to yourself and to the other coders checking out your code 6 | # And Python won't run this at all, or even notice it. 7 | 8 | # The # symbol is what creates a comment. 9 | # You can have a comment on a line all by itself 10 | 11 | # The print statement is a good place to start -- it allows us to see results right away. 12 | 13 | print "Or you can have a comment on the same line" # as a command that Python WILL run 14 | 15 | print "The print statement will output some text to the screen." # it doesn't print anything to paper. 16 | 17 | # Python will run commands from top to bottom, left to right 18 | 19 | # So the print statement on line 11 will run before the print statement on line 13 20 | 21 | 22 | 23 | 24 | print "You can use lots of newlines to space things out if you like" 25 | print "Or you can keep your statements close to one another." 26 | 27 | print "It's really up to you, but generally speaking, you'll want to make your code as readable as possible." 28 | 29 | # These two statements are identical 30 | print 4+4 31 | print 4 + 4 32 | 33 | # Indentation levels matter a lot, even if other kinds of whitespace like newlines or spacing don't matter as much 34 | 35 | # So if you uncommented the next line and ran this, you'd get an error. 36 | # print 4 + 4 37 | -------------------------------------------------------------------------------- /playtime/lesson04_group_csvtodict.py: -------------------------------------------------------------------------------- 1 | # Challenge Level: Advanced 2 | 3 | # Group exercise! 4 | 5 | # Scenario: Your organization has put on three events and you have a CSV with details about those events 6 | # You have the event's date, a brief description, its location, how many attended, how much it cost, and some brief notes 7 | # File: https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/events.csv 8 | 9 | # Goal: Read this CSV into a dictionary. 10 | 11 | # Your function should return a dictionary that looks something like this. 12 | # Bear in mind dictionaries have no order, so yours might look a little different! 13 | # Note that I 'faked' the order of my dictionary by using the row numbers as my keys. 14 | 15 | # {0: 16 | # {'attendees': '12', 17 | # 'description': 'Film Screening', 18 | # 'notes': 'Panel afterwards', 19 | # 'cost': '$10 suggested', 20 | # 'location': 'In-office', 21 | # 'date': '1/11/2014'}, 22 | 23 | # 1: 24 | # {'attendees': '12', 25 | # 'description': 'Happy Hour', 26 | # 'notes': 'Too loud', 27 | # 'cost': '0', 28 | # 'location': 'That bar with the drinks', 29 | # 'date': '2/22/2014'}, 30 | # 2: 31 | # {'attendees': '200', 32 | # 'description': 'Panel Discussion', 33 | # 'notes': 'Full capacity and 30 on waitlist', 34 | # 'cost': '0', 35 | # 'location': 'Partner Organization', 36 | # 'date': '3/31/2014'} 37 | # } -------------------------------------------------------------------------------- /section_10_(dictionaries)/dict_update.py: -------------------------------------------------------------------------------- 1 | # If you're new to dictionaries, you might want to start with dict_access.py 2 | 3 | # We create a dictionary. 4 | 5 | contacts = { 6 | 'Shannon': '202-555-1234', 7 | 'Amy': '410-515-3000', 8 | 'Jen': '301-600-5555', 9 | 'Julie': '202-333-9876' 10 | } 11 | 12 | # If we want to add a new item to a dictionary, we can use direct access to change it. 13 | contacts['Rachel'] = '202-888-1234' 14 | 15 | # We can do the same thing to change an existing dictionary item, too. 16 | contacts['Amy'] = '703-444-8888' 17 | 18 | # That's great for changing a dictionary one key at a time, but let's say we have a lot of updates. We have two options. 19 | 20 | new_contacts = { 21 | 'Kristin': '703-333-1234', 22 | 'Katie': '301-555-9876', 23 | 'Grace': '202-777-2222', 24 | 'Charlotte': '410-555-9999' 25 | } 26 | 27 | # Option 1: Loop through the changes one at a time. 28 | 29 | for name, phone in new_contacts.items(): 30 | contacts[name] = phone 31 | 32 | # Now contacts has everything in new_contacts. 33 | print contacts, "\n" 34 | 35 | 36 | # Let's set contacts back to the value it had before we added new_contacts. 37 | 38 | contacts = { 39 | 'Shannon': '202-555-1234', 40 | 'Amy': '410-515-3000', 41 | 'Jen': '301-600-5555', 42 | 'Julie': '202-333-9876', 43 | 'Rachel': '202-888-1234' 44 | } 45 | 46 | # Option 2: Use the dictionary method .update() 47 | 48 | contacts.update(new_contacts) 49 | 50 | print contacts -------------------------------------------------------------------------------- /playtime/lesson03_states.py: -------------------------------------------------------------------------------- 1 | # Challenge Level: Beginner 2 | 3 | # Background: You have a text file with all of the US state names: 4 | # states.txt: See section_07_(files). 5 | # 6 | # You also have a spreadsheet in comma separated value (CSV) format, state_info.csv. See also section_07_(files) 7 | # state_info.csv has the following columns: Population Rank, State Name, Population, US House Members, Percent of US Population 8 | 9 | # Challenge 1: Open states.txt and use the information to generate an HTML drop-down menu as in: https://github.com/shannonturner/python-lessons/blob/master/playtime/lesson02_states.py 10 | 11 | # Challenge 2: Save the HTML as states.html instead of printing it to screen. 12 | # Your states.html should look identical (or at least similar) to the one you created in the Lesson 2 playtime, except you're getting the states from a file instead of a list. 13 | 14 | # Challenge 3: Using state_info.csv, create an HTML page that has a table for *each* state with all of the state details. 15 | 16 | # Sample output: 17 | 18 | # 19 | # 20 | # 21 | # 22 | # 23 | # 24 | # 25 | # 26 | # 27 | # 28 | # 29 | # 30 | #
California
Rank: 1 Percent: 11.91%
US House Members: 53 Population: 38,332,521
31 | 32 | # Challenge 4 (Not a Python challenge, but an HTML/Javascript challenge): When you make a choice from the drop-down menu, jump to that state's table. -------------------------------------------------------------------------------- /playtime/lesson03_compare.py: -------------------------------------------------------------------------------- 1 | # Challenge Level: Advanced 2 | 3 | # NOTE: Please don't use anyone's *real* contact information during these exercises, especially if you're putting it up on Github! 4 | 5 | # Background: You took a survey of all of the employees at your organization to see what their twitter and github names were. You got a few responses. 6 | # You have two spreadsheets in CSV (comma separated value) format: 7 | # all_employees.csv: See section_07_(files). Contains all of the employees in your organization and their contact info. 8 | # Columns: name, email, phone, department, position 9 | # survey.csv: See section_07_(files). Contains info for employees who have completed a survey. Not all employees have completed the survey. 10 | # Columns: email, twitter, github 11 | 12 | # Challenge 1: Open all_employees.csv and survey.csv and compare the two. When an employee from survey.csv appears in all_employees.csv, print out the rest of their information from all_employees.csv. 13 | 14 | # Sample output: 15 | # Shannon Turner took the survey! Here is her contact information: Twitter: @svt827 Github: @shannonturner Phone: 202-555-1234 16 | 17 | # Challenge 2: Add the extra information from survey.csv into all_employees.csv as extra columns. 18 | # IMPORTANT: It would probably be a good idea to save it as an extra file instead of accidentally overwriting your original! 19 | # By the end, your all_employees.csv should contain the following columns: name, email, phone, department, position, twitter, github -------------------------------------------------------------------------------- /section_04_(lists)/list_basics.py: -------------------------------------------------------------------------------- 1 | # list basics: adding items, removing items, inserting items, slicing 2 | 3 | names = [] # an empty list 4 | print names 5 | 6 | names.append('Shannon') # add one item to the end of the list 7 | print names 8 | 9 | # Accessing names by slicing: 10 | print names[0] # Shannon 11 | 12 | # Inserting an item (not just adding it to the end): 13 | names.insert(0, 'Finn') 14 | print names 15 | 16 | # 0 is the slicing number for where you'd like to insert the item BEFORE 17 | # In other words, this will insert 'Finn' just *before* index 0 18 | 19 | many_more = ['Jake', 'Princess Bubblegum', 'Marceline the Vampire Queen', 'Peppermint Butler'] 20 | 21 | # Now we can add all of the names in many_more the end of the list 22 | names.extend(many_more) 23 | print names 24 | 25 | # Now we're going to go sugar-free, so everyone from the candy kingdom needs to go. 26 | # Let's remove Peppermint Butler and Princess Bubblegum from our list. 27 | 28 | names.pop() # this will remove the last item from the list, which happens to be Peppermint Butler 29 | print names 30 | 31 | names.pop(3) # this will remove the item at slicing number / index 3, which is Princess Bubblegum 32 | print names 33 | 34 | # Now we're going to search for an item and remove it. 35 | remove_this = names.index('Jake') 36 | print "I found Jake at slicing number / index #{0}".format(remove_this) 37 | print "Now I can use .pop() to remove that item." 38 | names.pop(remove_this) 39 | print names 40 | 41 | # We can also use .remove() to shortcut that. 42 | names.remove('Finn') 43 | print names -------------------------------------------------------------------------------- /section_06_(str-list)/quadrants_exercise.py: -------------------------------------------------------------------------------- 1 | # Exercise that you'll do in front of the group during the group exercise. 2 | # This is a rough approximation of the code that you'll end up with in the end. 3 | # This isn't how you'll start it off. 4 | # The first version of your code will be incomplete and a bit wrong. 5 | # You'll talk through the exercise, soliciting feedback from the class. 6 | # Be sure to ask lots of questions, especially "what do we expect is going to happen here?" 7 | # Each of the problem addresses is specifically designed to cause unexpected behavior if the program isn't written carefully. 8 | # It's a good thing to trip over these problem addresses. Students won't learn anything from seeing you do it perfectly in one go. But they'll learn a lot from the process of iterating, finding the problem, and improving. 9 | 10 | NW = [] 11 | NE = [] 12 | SE = [] 13 | SW = [] 14 | Other = [] 15 | 16 | address = "" # Enter your addresses here. 17 | # Problem 1: 123 SEA LANE SW 18 | # Problem 2: 456 fake st se 19 | # Problem 3: 678 lincoln ave 20 | 21 | print address 22 | 23 | address_as_list = address.upper().split(' ') 24 | 25 | if 'NW' in address_as_list: 26 | NW.append(address) 27 | elif 'NE' in address_as_list: 28 | NE.append(address) 29 | elif 'SE' in address_as_list: 30 | SE.append(address) 31 | elif 'SW' in address_as_list: 32 | SW.append(address) 33 | else: 34 | Other.append(address) 35 | 36 | print "NW is {0}".format(NW) 37 | print "NE is {0}".format(NE) 38 | print "SE is {0}".format(SE) 39 | print "SW is {0}".format(SW) 40 | print "Other is {0}".format(Other) 41 | -------------------------------------------------------------------------------- /section_02_(strings)/string_find.py: -------------------------------------------------------------------------------- 1 | # String methods: string.find() 2 | 3 | # string.find() tells you where you can find a part of one string in a larger string. 4 | # string.find() will return a number: 5 | # if string.find() returns -1, it could not find the string inside the larger string. 6 | # otherwise, string.find() will return the slicing number/index of where it found that string 7 | 8 | email_address = "hoorayforpython@notarealwebsite.com" 9 | 10 | print "I found the snail at: {0}".format(email_address.find("@")) # the slicing number/index of where the at symbol appears 11 | 12 | # string.find() + slicing = awesome! 13 | 14 | # Everything before the @ is part of the email_handle; everything after the @ is part of the domain where they have their email registered. 15 | # Let's use string.find() and slicing together to split those apart. 16 | 17 | at_symbol_index = email_address.find("@") 18 | 19 | print "I found the snail at: {0}".format(at_symbol_index) # Notice how line 10 and 19 each give the same result, but take a different approach 20 | 21 | email_handle = email_address[0:at_symbol_index] 22 | 23 | print "The email_handle is: {0}".format(email_handle) 24 | 25 | email_domain = email_address[at_symbol_index + 1:] # without the +1, the at symbol would be included. Notice that there is no number after the colon, so Python assumes you want everything to the end. 26 | 27 | print "The email_domain is: {0}".format(email_domain) 28 | 29 | print "When string.find() can't find a string, it'll give a -1. So since there's no 'QQQ' in email_address, this will return a -1: {0}".format(email_address.find("QQQ")) -------------------------------------------------------------------------------- /playtime/lesson03_contacts.py: -------------------------------------------------------------------------------- 1 | # Challenge Level: Beginner 2 | 3 | # NOTE: Please don't use anyone's *real* contact information during these exercises, especially if you're putting it up on Github! 4 | 5 | # Background: You have a dictionary with people's contact information. You want to display that information as an HTML table. 6 | 7 | contacts = { 8 | 'Shannon': {'phone': '202-555-1234', 'twitter': '@svt827', 'github': '@shannonturner' },
 9 | 'Beyonce': {'phone': '303-404-9876', 'twitter': '@beyonce', 'github': '@bey'}, 10 | 'Tegan and Sara': {'phone': '301-777-3313', 'twitter': '@teganandsara', 'github': '@heartthrob'} 11 | } 12 | 13 | # Goal 1: Loop through that dictionary to print out everyone's contact information. 14 | 15 | # Sample output: 16 | 17 | # Shannon's contact information is: 18 | # Phone: 202-555-1234 19 | # Twitter: @svt827 20 | # Github: @shannonturner
 21 | 22 | # Beyonce's contact information is: 23 | # Phone: 303-404-9876 24 | # Twitter: @beyonce 25 | # Github: @bey 26 | 27 | 28 | # Goal 2: Display that information as an HTML table. 29 | 30 | # Sample output: 31 | 32 | # 33 | # 34 | # 35 | # 36 | # 37 | # 38 | # 39 | # 40 | # 41 | #
Shannon
Phone: 202-555-1234 Twitter: @svt827 Github: @shannonturner
42 | 43 | # ... 44 | 45 | # Goal 3: Write all of the HTML out to a file called contacts.html and open it in your browser. 46 | 47 | # Goal 4: Instead of reading in the contacts from the dictionary above, read them in from contacts.csv, which you can find in lesson_07_(files). -------------------------------------------------------------------------------- /playtime/lesson02_states.py: -------------------------------------------------------------------------------- 1 | # Difficulty Level: Intermediate 2 | 3 | # Goal: Create a program that prints out an HTML drop down menu for all 50 states 4 | 5 | # Step 1: Define your list of states 6 | # These should all be strings, since they're names of places 7 | # Instead of having to type them all out, I really like liststates.com -- you can even customize the format it gives you the states in to make it super easy to copy/paste into your code here 8 | 9 | # Step 2: Create your loop 10 | # Essentially, you're telling Python: for each state in my list: print this HTML code 11 | # A good place to start is by printing the name of the state in the loop; after that you can add the HTML around it 12 | 13 | # Step 3: Add the HTML 14 | # A drop-down menu in HTML looks like this: 15 | 16 | # 19 | 20 | # At line 14, we create the drop-down menu 21 | # At line 15, we create one drop-down item. Each additional