├── .gitignore ├── _old ├── Course materials - Python 3 │ ├── Chapter 10 │ │ ├── Assignment solutions │ │ │ ├── 10-1 review exercises.py │ │ │ ├── 10-2 review exercises.py │ │ │ ├── 10-3 review exercises.py │ │ │ ├── csv_split.py │ │ │ ├── high_scores.py │ │ │ ├── remove_files.py │ │ │ └── sample_csv.csv │ │ └── Practice files │ │ │ ├── backup │ │ │ ├── images │ │ │ │ ├── additional files │ │ │ │ │ └── one last image.png │ │ │ │ ├── an image file.gif │ │ │ │ ├── another image.gif │ │ │ │ ├── one more image.gif │ │ │ │ └── png file - not a gif.png │ │ │ └── little pics │ │ │ │ ├── better not delete me.txt │ │ │ │ ├── look in here too │ │ │ │ └── definitely has to go.jpg │ │ │ │ ├── save me please.jpg │ │ │ │ └── to be deleted.jpg │ │ │ ├── example.txt │ │ │ ├── images │ │ │ ├── additional files │ │ │ │ └── one last image.png │ │ │ ├── an image file.gif │ │ │ ├── another image.gif │ │ │ ├── one more image.gif │ │ │ └── png file - not a gif.png │ │ │ ├── little pics │ │ │ ├── better not delete me.txt │ │ │ ├── look in here too │ │ │ │ └── definitely has to go.jpg │ │ │ ├── save me please.jpg │ │ │ └── to be deleted.jpg │ │ │ ├── pastimes.csv │ │ │ ├── poem.txt │ │ │ ├── scores.csv │ │ │ ├── tabbed wonka.csv │ │ │ └── wonka.csv │ ├── Chapter 12 │ │ ├── Assignment solutions │ │ │ ├── 12-1 review exercises.py │ │ │ ├── 12-2 review exercises.py │ │ │ └── cover_the_emperor.py │ │ └── Practice files │ │ │ ├── Emperor cover sheet.pdf │ │ │ ├── Pride and Prejudice.pdf │ │ │ ├── The Emperor.pdf │ │ │ ├── The Whistling Gypsy.pdf │ │ │ ├── Walrus.pdf │ │ │ ├── half and half.pdf │ │ │ ├── top secret.pdf │ │ │ └── ugly.pdf │ ├── Chapter 13 │ │ └── Assignment solutions │ │ │ └── 13-1 review exercises.py │ ├── Chapter 14 │ │ └── Assignment solutions │ │ │ ├── 14-1 review exercises.py │ │ │ └── 14-2 review exercises.py │ ├── Chapter 15 │ │ ├── Assignment solutions │ │ │ ├── 15-1 review exercises.py │ │ │ └── pirates.py │ │ └── Practice files │ │ │ └── pirates.csv │ ├── Chapter 16 │ │ └── Assignment solutions │ │ │ ├── 16-2 review exercises.py │ │ │ ├── partial_PDF.py │ │ │ └── poetry_writer.py │ ├── Chapter 17 │ │ ├── Assignment solutions │ │ │ └── login.py │ │ ├── first_app │ │ │ ├── app.yaml │ │ │ ├── hello.py │ │ │ └── temperature.py │ │ └── poetry │ │ │ ├── app.yaml │ │ │ └── makePoems.py │ ├── Chapter 2 │ │ └── Assignment solutions │ │ │ ├── 2-4 review exercises.py │ │ │ └── 2-5 review exercises.py │ ├── Chapter 4 │ │ └── Assignment solutions │ │ │ ├── 4-1 review exercises.py │ │ │ ├── 4-2 review exercises.py │ │ │ ├── 4-3 review exercises.py │ │ │ └── first_letter.py │ ├── Chapter 5 │ │ └── Assignment solutions │ │ │ ├── 5-1 review exercises.py │ │ │ ├── 5-2 review exercises.py │ │ │ ├── 5-3 review exercises.py │ │ │ └── translate.py │ ├── Chapter 6 │ │ └── Assignment solutions │ │ │ ├── 6-1 review exercises.py │ │ │ ├── 6-2 review exercises.py │ │ │ ├── 6-3 review exercises.py │ │ │ ├── exponent.py │ │ │ ├── invest.py │ │ │ └── temperature.py │ ├── Chapter 8 │ │ └── Assignment solutions │ │ │ ├── 8-1 review exercises.py │ │ │ ├── 8-2 review exercises.py │ │ │ ├── 8-3 review exercises.py │ │ │ ├── 8-4 review exercises.py │ │ │ ├── 8-5 review exercises.py │ │ │ ├── 8-6 review exercises.py │ │ │ ├── coin_toss.py │ │ │ ├── coin_toss_alternative.py │ │ │ ├── election.py │ │ │ └── factors.py │ ├── Chapter 9 │ │ └── Assignment solutions │ │ │ ├── 9-1 review exercises.py │ │ │ ├── 9-2 review exercises.py │ │ │ ├── 9-3 review exercises.py │ │ │ ├── capital_city_loop.py │ │ │ ├── capitals.py │ │ │ ├── cats_with_hats.py │ │ │ ├── cats_with_hats_alternative.py │ │ │ ├── cats_with_hats_dict.py │ │ │ ├── fundamental_review.py │ │ │ ├── list_of_lists.py │ │ │ └── poetry.py │ ├── oop │ │ ├── dog_class.py │ │ ├── dog_inheritence.py │ │ ├── dog_instance_methods.py │ │ ├── dog_isinstance.py │ │ ├── dog_walking.py │ │ ├── github_with_class.py │ │ ├── my_farm.py │ │ ├── oldest_dog.py │ │ ├── oop_comp_check.md │ │ └── pet_class.py │ └── regular_expressions │ │ ├── _clean_data.txt │ │ ├── _sloppy_data.txt │ │ ├── phone-book-fun.py │ │ ├── phone_list.py │ │ ├── regex-groups.py │ │ ├── regex-namedgroups.py │ │ ├── regex-validation-refactor.py │ │ ├── regex-validation.py │ │ ├── regex_answers.txt │ │ └── regex_review.py └── Course materials │ ├── Chapter 10 │ ├── Assignment solutions │ │ ├── 10-1 review exercises.py │ │ ├── 10-2 review exercises.py │ │ ├── 10-3 review exercises.py │ │ ├── csv_split.py │ │ ├── high_scores.py │ │ ├── remove_files.py │ │ └── sample_csv.csv │ └── Practice files │ │ ├── backup │ │ ├── images │ │ │ ├── additional files │ │ │ │ └── one last image.png │ │ │ ├── an image file.gif │ │ │ ├── another image.gif │ │ │ ├── one more image.gif │ │ │ └── png file - not a gif.png │ │ └── little pics │ │ │ ├── better not delete me.txt │ │ │ ├── look in here too │ │ │ └── definitely has to go.jpg │ │ │ ├── save me please.jpg │ │ │ └── to be deleted.jpg │ │ ├── example.txt │ │ ├── images │ │ ├── additional files │ │ │ └── one last image.png │ │ ├── an image file.gif │ │ ├── another image.gif │ │ ├── one more image.gif │ │ └── png file - not a gif.png │ │ ├── little pics │ │ ├── better not delete me.txt │ │ ├── look in here too │ │ │ └── definitely has to go.jpg │ │ ├── save me please.jpg │ │ └── to be deleted.jpg │ │ ├── output.txt │ │ ├── pastimes.csv │ │ ├── poem.txt │ │ ├── scores.csv │ │ ├── tabbed wonka.csv │ │ └── wonka.csv │ ├── Chapter 12 │ ├── Assignment solutions │ │ ├── 12-1 review exercises.py │ │ ├── 12-2 review exercises.py │ │ └── cover_the_emperor.py │ ├── Practice files │ │ ├── Emperor cover sheet.pdf │ │ ├── Pride and Prejudice.pdf │ │ ├── The Emperor.pdf │ │ ├── The Whistling Gypsy.pdf │ │ ├── Walrus.pdf │ │ ├── half and half.pdf │ │ ├── top secret.pdf │ │ └── ugly.pdf │ ├── basic_pdf.py │ ├── hello.pdf │ ├── hello_again.pdf │ ├── less_basic_pdf.py │ ├── table_pdf.py │ └── tps_report.pdf │ ├── Chapter 13 │ └── Assignment solutions │ │ └── 13-1 review exercises.py │ ├── Chapter 14 │ └── Assignment solutions │ │ ├── 14-1 review exercises.py │ │ ├── 14-2 review exercises.py │ │ ├── 14-3 review exercises.py │ │ └── 14-4 review exercises.py │ ├── Chapter 15 │ ├── Assignment solutions │ │ ├── 15-1 review exercises.py │ │ └── pirates.py │ └── Practice files │ │ └── pirates.csv │ ├── Chapter 16 │ └── Assignment solutions │ │ ├── 16-2 review exercises.py │ │ ├── partial_PDF.py │ │ └── poetry_writer.py │ ├── Chapter 17 │ ├── Assignment solutions │ │ └── login.py │ ├── first_app │ │ ├── app.yaml │ │ ├── hello.py │ │ └── temperature.py │ └── poetry │ │ ├── app.yaml │ │ └── makePoems.py │ ├── Chapter 2 │ └── Assignment solutions │ │ ├── 2-4 review exercises.py │ │ └── 2-5 review exercises.py │ ├── Chapter 4 │ └── Assignment solutions │ │ ├── 4-1 review exercises.py │ │ ├── 4-2 review exercises.py │ │ ├── 4-3 review exercises.py │ │ └── first_letter.py │ ├── Chapter 5 │ └── Assignment solutions │ │ ├── 5-1 review exercises.py │ │ ├── 5-2 review exercises.py │ │ ├── 5-3 review exercises.py │ │ └── translate.py │ ├── Chapter 6 │ └── Assignment solutions │ │ ├── 6-1 review exercises.py │ │ ├── 6-2 review exercises.py │ │ ├── 6-3 review exercises.py │ │ ├── exponent.py │ │ ├── invest.py │ │ └── temperature.py │ ├── Chapter 8 │ └── Assignment solutions │ │ ├── 8-1 review exercises.py │ │ ├── 8-2 review exercises.py │ │ ├── 8-3 review exercises.py │ │ ├── 8-4 review exercises.py │ │ ├── 8-5 review exercises.py │ │ ├── 8-6 review exercises.py │ │ ├── coin_toss.py │ │ ├── coin_toss_alternative.py │ │ ├── election.py │ │ └── factors.py │ ├── Chapter 9 │ └── Assignment solutions │ │ ├── 9-1 review exercises.py │ │ ├── 9-2 review exercises.py │ │ ├── 9-3 review exercises.py │ │ ├── capital_city_loop.py │ │ ├── capitals.py │ │ ├── cats_with_hats.py │ │ ├── cats_with_hats_alternative.py │ │ ├── cats_with_hats_dict.py │ │ ├── fundamental_review.py │ │ ├── list_of_lists.py │ │ └── poetry.py │ ├── oop │ ├── dog_class.py │ ├── dog_inheritence.py │ ├── dog_instance_methods.py │ ├── dog_isinstance.py │ ├── dog_walking.py │ ├── github_with_class.py │ ├── my_farm.py │ ├── oldest_dog.py │ ├── oop_comp_check.md │ └── pet_class.py │ └── regular_expressions │ ├── _clean_data.txt │ ├── _sloppy_data.txt │ ├── phone-book-fun.py │ ├── phone_list.py │ ├── regex-groups.py │ ├── regex-namedgroups.py │ ├── regex-validation-refactor.py │ ├── regex-validation.py │ ├── regex_answers.txt │ └── regex_review.py ├── chp01 ├── 1-1.py └── 1-2.py ├── chp03 ├── 3-1.py ├── 3-2.py ├── 3-3.py └── first_letter.py ├── chp04 ├── 4-1.py ├── 4-2.py ├── 4-3.py └── translate.py ├── chp05 ├── 5-1.py ├── 5-2.py ├── exponent.py ├── invest.py └── temperature.py ├── chp07 ├── 7-1.py ├── 7-2.py ├── 7-3.py ├── 7-4.py ├── 7-5.py ├── 7-6.py ├── coin_toss.py ├── coin_toss_alternative.py ├── coin_toss_functions.py ├── election.py └── factors.py ├── chp08 ├── 8-1.py ├── 8-2.py ├── 8-3.py ├── capital_city_loop.py ├── capitals.py ├── cats_with_hats.py ├── cats_with_hats_alternative.py ├── cats_with_hats_dict.py ├── fundamental_review.py ├── list_of_lists.py └── poetry.py ├── chp09 ├── practice_files │ ├── backup │ │ ├── images │ │ │ ├── additional files │ │ │ │ └── one last image.png │ │ │ ├── an image file.gif │ │ │ ├── another image.gif │ │ │ ├── one more image.gif │ │ │ └── png file - not a gif.png │ │ └── little pics │ │ │ ├── better not delete me.txt │ │ │ ├── look in here too │ │ │ └── definitely has to go.jpg │ │ │ ├── save me please.jpg │ │ │ └── to be deleted.jpg │ ├── example.txt │ ├── images │ │ ├── additional files │ │ │ └── one last image.png │ │ ├── an image file.gif │ │ ├── another image.gif │ │ ├── one more image.gif │ │ └── png file - not a gif.png │ ├── little pics │ │ ├── better not delete me.txt │ │ ├── look in here too │ │ │ └── definitely has to go.jpg │ │ ├── save me please.jpg │ │ └── to be deleted.jpg │ ├── pastimes.csv │ ├── poem.txt │ ├── scores.csv │ ├── tabbed wonka.csv │ └── wonka.csv └── solutions │ ├── 9-1.py │ ├── 9-2.py │ ├── 9-3.py │ ├── csv_split.py │ ├── high_scores.py │ ├── remove_files.py │ └── sample_csv.csv ├── chp11 ├── practice_files │ ├── Emperor cover sheet.pdf │ ├── Pride and Prejudice.pdf │ ├── The Emperor.pdf │ ├── The Whistling Gypsy.pdf │ ├── Walrus.pdf │ ├── half and half.pdf │ ├── top secret.pdf │ └── ugly.pdf └── solutions │ ├── 11-1.py │ ├── 11-2.py │ └── cover_the_emperor.py ├── chp12 └── 12-1.py ├── chp13 ├── 13-1.py ├── 13-2.py ├── 13-3.py └── 13-4.py ├── chp14 ├── practice_files │ └── pirates.csv └── solutions │ ├── 14-1.py │ └── pirates.py ├── chp15 ├── 15-1.py ├── partial_PDF.py └── poetry_writer.py ├── chp18 ├── _clean_data.txt ├── _sloppy_data.txt ├── phone-book-fun.py ├── phone_list.py ├── regex-groups.py ├── regex-namedgroups.py ├── regex-validation-refactor.py ├── regex-validation.py ├── regex_answers.txt └── regex_review.py ├── chp19 ├── dog_class.py ├── dog_inheritance.py ├── dog_instance_methods.py ├── dog_isinstance.py ├── dog_walking.py ├── github_with_class.py ├── my_farm.py ├── oldest_dog.py ├── oop_comp_check.md └── pet_class.py └── readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | py3venv 2 | env 3 | *.pyc 4 | __pycache__/ 5 | .DS_Store -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Assignment solutions/10-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 10.1 review exercises 2 | 3 | 4 | ''' 5 | In order to run correctly, this script first needs to 6 | be placed in the Chapter 10 "Practice files" folder. 7 | (File paths are covered in section 10.2) 8 | ''' 9 | 10 | # Read a text file by looping over individual lines 11 | my_poem = open("poem.txt", "r") 12 | for line in my_poem.readlines(): 13 | # Replace automatic line break at end of line; 14 | # file already contains newline characters 15 | print(line,) 16 | my_poem.close() 17 | 18 | # Print some blank lines to separate the two examples 19 | print("\n\n") 20 | 21 | # Use "with" to automatically close a file when finished 22 | with open("poem.txt", "r") as my_poem: 23 | for line in my_poem.readlines(): 24 | print(line,) 25 | 26 | # Write the contents of one file into another, line-by-line 27 | poem_in = open("poem.txt", "r") 28 | poem_out = open("output.txt", "w") 29 | for line in poem_in.readlines(): 30 | poem_out.write(line) 31 | poem_in.close() 32 | poem_out.close() 33 | 34 | # Repeat the previous exercise using the "with" keyword 35 | # (This will overwrite the previous output file.) 36 | with open("poem.txt", "r") as poem_in, open("output.txt", "w") as poem_out: 37 | for line in poem_in.readlines(): 38 | poem_out.write(line) 39 | 40 | 41 | # Append a new line to the end of "output.txt" 42 | # (Need to start on a new line, so add "\n" to the beginning.) 43 | with open("output.txt", "a") as poem_append: 44 | poem_append.write("\nThus ends the haiku.") 45 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Assignment solutions/10-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 10.2 review exercises 2 | 3 | 4 | # Initial setup 5 | import os 6 | import glob 7 | # This path may need to be changed depending on your setup 8 | path = "C:/Real Python/Course Materials - Python 3/Chapter 10/Practice files/images" 9 | 10 | 11 | # Display the full paths of all files and folders in the main "images" folder 12 | print('Full contents of "images" folder:') 13 | for file_name in os.listdir(path): 14 | print(os.path.join(path, file_name)) 15 | 16 | # Display the full paths of any PNG files in the "images" folder 17 | file_matches = os.path.join(path, "*.png") 18 | print('All PNG files in "images" folder:') 19 | for file_name in glob.glob(file_matches): 20 | print(file_name) 21 | 22 | # Change all PNGs to JPGs in the "images" folder and its subfolders 23 | # Could use indexing to get the file extension, but try using os.path.splitext() 24 | for current_folder, subfolders, file_names in os.walk(path): 25 | for file_name in file_names: 26 | file_path = os.path.join(current_folder, file_name) 27 | file_tuple = os.path.splitext(file_path) # split into (path, extension) 28 | if file_tuple[1].lower() == ".png": # check if extension is PNG 29 | pass # os.rename(file_path, file_tuple[0] + ".jpg") 30 | 31 | # Check that the two files have been converted to JPGs successfully 32 | print(os.path.exists(os.path.join(path, "png file - not a gif.jpg"))) 33 | print(os.path.exists(os.path.join(path, "additional files/one last image.jpg"))) 34 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Assignment solutions/10-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 10.3 review exercises 2 | 3 | 4 | # Initial setup 5 | import os 6 | import csv 7 | # This path may need to be changed depending on your setup 8 | path = "C:/Real Python/Course Materials/Chapter 10/Practice files" 9 | 10 | 11 | # Read in a CSV and display each row except the header row 12 | # Append a third column and write out the resulting CSV with a new header 13 | in_file_path = os.path.join(path, "pastimes.csv") 14 | out_file_path = os.path.join(path, "Output/categorized pastimes.csv") 15 | with open(in_file_path, "rb") as inFile, open(out_file_path, "wb") as outFile: 16 | csv_reader = csv.reader(inFile) 17 | csv_writer = csv.writer(outFile) 18 | 19 | # skip header row and write a new output header row 20 | csv_reader.next() 21 | csv_writer.writerow(["Name", "Favorite Pastime", "Type of pastime"]) 22 | 23 | for row in csv_reader: 24 | print row 25 | # Check if "Favorite Pastime" includes "fighting" 26 | if row[1].lower().find("fighting") != -1: 27 | row.append("Combat") 28 | else: 29 | row.append("Other") 30 | # Add the new row to the output 31 | csv_writer.writerow(row) 32 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Assignment solutions/high_scores.py: -------------------------------------------------------------------------------- 1 | # 10.3 high_scores.py 2 | # Read in CSV data containing names and scores; display a high score list 3 | 4 | import csv 5 | import os 6 | my_path = "C:/Real Python/Course materials/Chapter 10/Practice files" 7 | 8 | high_scores_dict = {} 9 | with open(os.path.join(my_path, "scores.csv"), "rb") as myFile: 10 | my_file_reader = csv.reader(myFile) 11 | for name, score in my_file_reader: # get each name/score pair 12 | score = int(score) # convert string score to integer 13 | if name in high_scores_dict: # already had an entry for that name 14 | if score > high_scores_dict[name]: # new score is higher 15 | high_scores_dict[name] = score 16 | else: # haven't seen this name yet; add it to dictionary 17 | high_scores_dict[name] = score 18 | 19 | for name in sorted(high_scores_dict): 20 | print name, high_scores_dict[name] 21 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Assignment solutions/remove_files.py: -------------------------------------------------------------------------------- 1 | # 10.2 remove_files.py 2 | # Remove JPG files from multiple folders based on file size 3 | 4 | import os 5 | 6 | path = "C:/Real Python/Course materials/Chapter 10/Practice files/little pics" 7 | for current_folder, subfolders, file_names in os.walk(path): 8 | for file_name in file_names: 9 | full_path = os.path.join(current_folder, file_name) 10 | # check if file is a JPG 11 | check_JPG = file_name.lower().endswith(".jpg") 12 | # check if size is less than 2Kb 13 | check_size = os.path.getsize(full_path) < 2000 14 | if check_JPG and check_size: # both conditions must be True 15 | print 'Deleting "{}"...'.format(file_name) 16 | os.remove(full_path) 17 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/additional files/one last image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/additional files/one last image.png -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/an image file.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/an image file.gif -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/another image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/another image.gif -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/one more image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/one more image.gif -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/png file - not a gif.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/backup/images/png file - not a gif.png -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/backup/little pics/better not delete me.txt: -------------------------------------------------------------------------------- 1 | hi mom -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/backup/little pics/look in here too/definitely has to go.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/backup/little pics/look in here too/definitely has to go.jpg -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/backup/little pics/save me please.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/backup/little pics/save me please.jpg -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/backup/little pics/to be deleted.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/backup/little pics/to be deleted.jpg -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/example.txt: -------------------------------------------------------------------------------- 1 | Hi there. 2 | This is a simple text file. 3 | If you can read me, congratulations! -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/images/additional files/one last image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/images/additional files/one last image.png -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/images/an image file.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/images/an image file.gif -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/images/another image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/images/another image.gif -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/images/one more image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/images/one more image.gif -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/images/png file - not a gif.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/images/png file - not a gif.png -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/little pics/better not delete me.txt: -------------------------------------------------------------------------------- 1 | hi mom -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/little pics/look in here too/definitely has to go.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/little pics/look in here too/definitely has to go.jpg -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/little pics/save me please.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/little pics/save me please.jpg -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/little pics/to be deleted.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 10/Practice files/little pics/to be deleted.jpg -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/pastimes.csv: -------------------------------------------------------------------------------- 1 | Person,Favorite pastime 2 | Fezzik,Fighting 3 | Westley,Winning 4 | Inigo Montoya,Sword fighting 5 | Buttercup,Complaining 6 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/poem.txt: -------------------------------------------------------------------------------- 1 | This is the first line 2 | The second line is longer 3 | Hippopotamus -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/scores.csv: -------------------------------------------------------------------------------- 1 | LLCoolDave,23 2 | LLCoolDave,27 3 | red,12 4 | LLCoolDave,26 5 | tom123,26 6 | O_O,7 7 | Misha46,24 8 | O_O,14 9 | Empiro,18 10 | Empiro,18 11 | MaxxT,25 12 | L33tH4x,42 13 | Misha46,25 14 | johnsmith,30 15 | Empiro,23 16 | O_O,22 17 | MaxxT,25 18 | Misha46,24 19 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/tabbed wonka.csv: -------------------------------------------------------------------------------- 1 | First name Last name Reward 2 | Charlie Bucket golden ticket, chocolate factory 3 | Veruca Salt squirrel revolution 4 | Violet Beauregarde fruit chew 5 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 10/Practice files/wonka.csv: -------------------------------------------------------------------------------- 1 | First name,Last name,Reward 2 | Charlie,Bucket,"golden ticket, chocolate factory" 3 | Veruca,Salt,squirrel revolution 4 | Violet,Beauregarde,fruit chew 5 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Assignment solutions/12-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 12.1 review exercises 2 | 3 | 4 | import os 5 | from pyPdf import PdfFileReader, PdfFileWriter 6 | 7 | path = "C:/Real Python/Course materials/Chapter 12/Practice files" 8 | input_file_name = os.path.join(path, "The Whistling Gypsy.pdf") 9 | input_file = PdfFileReader(file(input_file_name, "rb")) 10 | 11 | # Display meta-data about file 12 | print("Title:", input_file.getDocumentInfo().title) 13 | print("Author:", input_file.getDocumentInfo().author) 14 | print("Number of pages:", input_file.getNumPages()) 15 | 16 | # Specify and open output text file 17 | output_file_name = os.path.join(path, "Output/The Whistling Gypsy.txt") 18 | with open(output_file_name, "w") as output_file: 19 | # Extract every page of text 20 | for page_num in range(0, input_file.getNumPages()): 21 | text = input_file.getPage(page_num).extractText() 22 | text = text.encode("utf-8") # convert text to unicode 23 | output_file.write(text) 24 | 25 | # Save file without cover page 26 | output_PDF = PdfFileWriter() 27 | for page_num in range(1, input_file.getNumPages()): 28 | output_PDF.addPage(input_file.getPage(page_num)) 29 | 30 | output_file_name = os.path.join(path, "Output/The Whistling Gypsy un-covered.pdf") 31 | with file(output_file_name, "wb") as output_file: 32 | output_PDF.write(output_file) 33 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Assignment solutions/12-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 12.2 review exercises 2 | 3 | import os 4 | import copy 5 | from pyPdf import PdfFileReader, PdfFileWriter 6 | 7 | path = "C:/Real Python/Course materials/Chapter 12/Practice files" 8 | input_file_name = os.path.join(path, "Walrus.pdf") 9 | input_file = PdfFileReader(file(input_file_name, "rb")) 10 | output_PDF = PdfFileWriter() 11 | 12 | input_file.decrypt("IamtheWalrus") # decrypt the input file 13 | 14 | for page_num in range(0, input_file.getNumPages()): 15 | # rotate pages (call everything page_left for now; will make a copy) 16 | page_left = input_file.getPage(page_num) 17 | page_left.rotateCounterClockwise(90) 18 | 19 | page_right = copy.copy(page_left) # split each page in half 20 | upper_right = page_left.mediaBox.upperRight # get original page corner 21 | 22 | # crop and add left-side page 23 | page_left.mediaBox.upperRight = (upper_right[0]/2, upper_right[1]) 24 | output_PDF.addPage(page_left) 25 | # crop and add right-side page 26 | page_right.mediaBox.upperLeft = (upper_right[0]/2, upper_right[1]) 27 | output_PDF.addPage(page_right) 28 | 29 | # save new pages to an output file 30 | output_file_name = os.path.join(path, "Output/Updated Walrus.pdf") 31 | with file(output_file_name, "wb") as output_file: 32 | output_PDF.write(output_file) 33 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Assignment solutions/cover_the_emperor.py: -------------------------------------------------------------------------------- 1 | # 8.2 cover_the_emperor.py 2 | # Add a cover sheet to a PDF; save the full output as a new PDF 3 | 4 | import os 5 | from pyPdf import PdfFileReader, PdfFileWriter 6 | 7 | path = "C:/Real Python/Course materials/Chapter 12/Practice files" 8 | input_file_name1 = os.path.join(path, "Emperor cover sheet.pdf") 9 | input_file1 = PdfFileReader(file(input_file_name1, "rb")) 10 | input_file_name2 = os.path.join(path, "The Emperor.pdf") 11 | input_file2 = PdfFileReader(file(input_file_name2, "rb")) 12 | output_PDF = PdfFileWriter() 13 | 14 | # Read in all pages from the cover sheet PDF file 15 | for page_num in range(0, input_file1.getNumPages()): 16 | page = input_file1.getPage(page_num) 17 | output_PDF.addPage(page) 18 | 19 | # Read in all pages from "The Emperor.pdf" into the same output file 20 | for page_num in range(0, input_file2.getNumPages()): 21 | page = input_file2.getPage(page_num) 22 | output_PDF.addPage(page) 23 | 24 | # Output the results into a new PDF 25 | output_file_name = os.path.join(path, "Output/The Covered Emperor.pdf") 26 | output_file = file(output_file_name, "wb") 27 | output_PDF.write(output_file) 28 | output_file.close() 29 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Practice files/Emperor cover sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 12/Practice files/Emperor cover sheet.pdf -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Practice files/Pride and Prejudice.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 12/Practice files/Pride and Prejudice.pdf -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Practice files/The Emperor.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 12/Practice files/The Emperor.pdf -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Practice files/The Whistling Gypsy.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 12/Practice files/The Whistling Gypsy.pdf -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Practice files/Walrus.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 12/Practice files/Walrus.pdf -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Practice files/half and half.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 12/Practice files/half and half.pdf -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Practice files/top secret.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 12/Practice files/top secret.pdf -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 12/Practice files/ugly.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials - Python 3/Chapter 12/Practice files/ugly.pdf -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 13/Assignment solutions/13-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 13.1 review exercises 2 | 3 | import sqlite3 4 | 5 | # Create a temporary database connection in RAM 6 | with sqlite3.connect(':memory:') as connection: 7 | c = connection.cursor() 8 | 9 | # Create a "Roster" table with Name, Species and IQ fields 10 | c.execute("CREATE TABLE Roster(Name TEXT, Species TEXT, IQ INT)") 11 | 12 | # Add some data into the database 13 | roster_data = ( 14 | ("Jean-Baptiste Zorg", "Human", 122), 15 | ("Korben Dallas", "Meat Popsicle", 100), 16 | ("Ak'not", "Mangalore", -5) 17 | ) 18 | c.executemany("INSERT INTO Roster VALUES(?, ?, ?)", roster_data) 19 | 20 | # Update the Species of Korben Dallas to "Human" 21 | c.execute("UPDATE Roster SET Species=? WHERE Name=?", 22 | ('Human', 'Korben Dallas')) 23 | 24 | # Display the names and IQs of everyone classified as Human 25 | c.execute("SELECT Name, IQ FROM Roster WHERE Species = 'Human'") 26 | for row in c.fetchall(): 27 | print(row) 28 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 14/Assignment solutions/14-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 14.1 review exercises 2 | 3 | from urllib.request import urlopen 4 | 5 | # Get the full HTML from the "dionysus" page 6 | my_address = "https://realpython.com/practice/dionysus.html" 7 | html_page = urlopen(my_address) 8 | html_text = html_page.read().decode('utf-8') 9 | 10 | # Get the "Name" and "Favorite Color" using find() 11 | for tag in ["Name: ", "Favorite Color: "]: 12 | tag_start = html_text.find(tag) + len(tag) 13 | tag_end = html_text[tag_start:].find("<") 14 | # Remove extra spaces and newline padding 15 | print(html_text[tag_start:tag_start+tag_end].strip(" \n")) 16 | 17 | 18 | # Get the "Name" and "Favorite Color" using regular expressions 19 | import re 20 | # Match anything up until a new line or HTML tag; non-greedy 21 | for tag in ["Name: .*?[\n<]", "Favorite Color: .*?[\n<]"]: 22 | match_results = re.search(tag, html_text) 23 | # Remove the "Name: " or "Favorite Color: " label from first result 24 | result = re.sub(".*: ", "", match_results.group()) 25 | # Remove extra spaces and newline padding along with opening HTML tag 26 | print(result.strip(" \n<")) 27 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 14/Assignment solutions/14-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 14.2 review exercises 2 | 3 | from urllib.request import urlopen 4 | from bs4 import BeautifulSoup 5 | 6 | # Get the full HTML from the "profiles" page 7 | base_URL = "https://realpython.com/practice/" 8 | address = base_URL + "profiles.html" 9 | html_page = urlopen(address) 10 | html_text = html_page.read().decode('utf-8') 11 | soup = BeautifulSoup(html_text) 12 | 13 | # Parse out all the values of the page links 14 | for anchor in soup.find_all("a"): 15 | # Could also have used urlparse.urljoin() to get absolute URL 16 | link_address = base_URL + anchor["href"] 17 | # Display the text in the HTML page of each link 18 | link_page = urlopen(link_address) 19 | link_text = link_page.read().decode('utf-8') 20 | link_soup = BeautifulSoup(link_text) 21 | print(link_soup.get_text()) 22 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 15/Assignment solutions/15-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 15.1 review exercises 2 | 3 | # Setup 4 | import numpy 5 | 6 | 7 | # Create a 3x3 array of the number 3 through 11 using reshape() 8 | first_matrix = numpy.arange(3, 12) 9 | first_matrix = first_matrix.reshape(3, 3) 10 | 11 | # Display the min, max and mean of all entries in the matrix 12 | print "Min is", first_matrix.min() 13 | print "Max is", first_matrix.max() 14 | print "Mean is", first_matrix.mean() 15 | 16 | # Square every entry and save in a new matrix 17 | second_matrix = first_matrix ** 2 18 | 19 | # Put first_matrix on top of second_matrix 20 | third_matrix = numpy.vstack([first_matrix, second_matrix]) 21 | 22 | # Calculate the dot product of third_matrix by first_matrix 23 | print(numpy.dot(third_matrix, first_matrix)) 24 | 25 | # Reshape third_matrix into a 3x3x2 matrix 26 | third_matrix = third_matrix.reshape(3, 3, 2) 27 | print(third_matrix) 28 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 15/Assignment solutions/pirates.py: -------------------------------------------------------------------------------- 1 | # 15.2 pirates.py 2 | # Graph pirates versus global warming 3 | 4 | from matplotlib import pyplot as plt 5 | import csv 6 | import os 7 | path = "C:/Real Python/Course materials/Chapter 15/Practice files" 8 | 9 | years = [] 10 | temperatures = [] 11 | pirates = [] 12 | 13 | with open(os.path.join(path, "pirates.csv"), "rb") as my_file: 14 | my_file_reader = csv.reader(my_file) 15 | my_file_reader.next() # skip header row 16 | for year, temperature, pirate_count in my_file_reader: 17 | years.append(year) 18 | temperatures.append(temperature) 19 | pirates.append(pirate_count) 20 | 21 | plt.plot(pirates, temperatures, "r-o") 22 | 23 | # label graph 24 | plt.title("Global temperature as a function of pirate population") 25 | plt.xlabel("Total pirates") 26 | plt.ylabel("Average global temperature (Celsius)") 27 | plt.axis([-300, 48000, 14, 16]) 28 | 29 | # annotate points with years 30 | for i in range(0, len(years)): 31 | plt.annotate(str(years[i]), xy=(pirates[i], temperatures[i])) 32 | 33 | # save and display graph 34 | plt.savefig(os.path.join(path, "Output/pirates.png")) 35 | plt.show() 36 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 15/Practice files/pirates.csv: -------------------------------------------------------------------------------- 1 | Year,Temperature,Pirates 2 | 1820,14.25,45000 3 | 1860,14.4,35000 4 | 1880,14.55,20000 5 | 1920,14.9,15000 6 | 1940,15.25,5000 7 | 1980,15.6,400 8 | 2000,15.9,17 9 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 16/Assignment solutions/16-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 16.2 review exercises 2 | 3 | # Create a button that takes on the value in an entry box 4 | 5 | 6 | from Tkinter import * 7 | 8 | 9 | def button_clicked(): 10 | ''' sets the button text to the text in the entry box ''' 11 | button.config(text=entry.get()) 12 | 13 | 14 | window = Tk() 15 | # Create and add button 16 | button = Button(text=" ", command=button_clicked) 17 | button.grid(row=1, column=1) 18 | # Create and add space for user entry of text 19 | entry = Entry(width=10) 20 | entry.grid(row=1, column=2) 21 | 22 | mainloop() 23 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 17/Assignment solutions/login.py: -------------------------------------------------------------------------------- 1 | # 17-1 review exercise 2 | 3 | # This script needs to be placed in a project folder with 4 | # the appropriate YAML configuration file 5 | 6 | import webapp2 7 | 8 | 9 | class MainPage(webapp2.RequestHandler): 10 | def get(self): 11 | username = self.request.get("myName") 12 | if username == "": 13 | welcome_string = "" 14 | else: 15 | welcome_string = "Hi there, {}!".format(username) 16 | 17 | self.response.headers["Content-Type"] = "text/html" 18 | self.response.write(""" 19 | 20 | Enter your name... 21 | 22 | {}
23 |
24 |
25 | 26 |
27 | 28 | """.format(welcome_string)) 29 | 30 | routes = [('/', MainPage)] 31 | my_app = webapp2.WSGIApplication(routes, debug=True) 32 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 17/first_app/app.yaml: -------------------------------------------------------------------------------- 1 | application: temperature-converter 2 | version: 1 3 | runtime: python27 4 | api_version: 1 5 | threadsafe: false 6 | 7 | handlers: 8 | - url: /.* 9 | script: temperature.my_app 10 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 17/first_app/hello.py: -------------------------------------------------------------------------------- 1 | import webapp2 2 | import cgi 3 | 4 | 5 | class MainPage(webapp2.RequestHandler): 6 | def get(self): 7 | self.response.headers["Content-Type"] = "text/html" 8 | self.response.write(""" 9 | 10 | Enter your name... 11 | 12 |
13 |
14 | 15 |
16 | 17 | """) 18 | 19 | 20 | class Greeting(webapp2.RequestHandler): 21 | def post(self): 22 | username = cgi.escape(self.request.get("myName")) 23 | welcome_string = """ 24 | Hi there, {}! 25 | """.format(username) 26 | self.response.headers["Content-Type"] = "text/html" 27 | self.response.write(welcome_string) 28 | 29 | routes = [('/', MainPage), ('/welcome', Greeting)] 30 | my_app = webapp2.WSGIApplication(routes, debug=True) 31 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 17/first_app/temperature.py: -------------------------------------------------------------------------------- 1 | import webapp2 2 | 3 | 4 | def convert_temp(cel_temp): 5 | ''' convert Celsius temperature to Fahrenheit temperature ''' 6 | if cel_temp == "": 7 | return "" 8 | try: 9 | far_temp = float(cel_temp) * 9/5 + 32 10 | far_temp = round(far_temp, 3) # round to three decimal places 11 | return str(far_temp) 12 | except ValueError: # user entered non-numeric temperature 13 | return "invalid input" 14 | 15 | 16 | class MainPage(webapp2.RequestHandler): 17 | def get(self): 18 | cel_temp = self.request.get("cel_temp") 19 | far_temp = convert_temp(cel_temp) 20 | 21 | self.response.headers["Content-Type"] = "text/html" 22 | self.response.write(""" 23 | 24 | Temperature Converter 25 | 26 |
27 | Celsius temperature: 29 |
30 | Fahrenheit temperature: {} 31 |
32 | 33 | """.format(cel_temp, far_temp)) 34 | 35 | routes = [('/', MainPage)] 36 | my_app = webapp2.WSGIApplication(routes, debug=True) 37 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 17/poetry/app.yaml: -------------------------------------------------------------------------------- 1 | application: poem-generator 2 | version: 1 3 | runtime: python27 4 | api_version: 1 5 | threadsafe: false 6 | 7 | handlers: 8 | - url: /.* 9 | script: makePoems.my_app 10 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 2/Assignment solutions/2-4 review exercises.py: -------------------------------------------------------------------------------- 1 | # 2.4 review exercises 2 | 3 | 4 | ''' The following line won't run because of a syntax error ''' 5 | print("hi) 6 | 7 | # We didn't close the double quotes at the end of the string. 8 | # The line above needed to have been: 9 | # print("hi") 10 | 11 | 12 | ''' The following lines won't run properly, 13 | even if the syntax error in the line above is corrected, 14 | because of a run-time error ''' 15 | print(hello) 16 | 17 | # We meant to print the string "hello"; 18 | # a variable named 'hello' doesn't exist yet. 19 | # This line could have been: 20 | # myString = "hello" 21 | # print(myString) 22 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 2/Assignment solutions/2-5 review exercises.py: -------------------------------------------------------------------------------- 1 | # 2.5 review exercises 2 | 3 | # The following lines can also be typed 4 | # directly into the interactive window as well: 5 | 6 | 7 | # display a string directly 8 | print("hello") 9 | 10 | 11 | # display the contents of a string variable 12 | my_string = "hi" 13 | print(my_string) 14 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 4/Assignment solutions/4-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 4.1 review exercises 2 | 3 | print('There are "double quotes" in this string.') 4 | 5 | print("This string's got an apostrophe.") 6 | 7 | print('''This string was written on multiple lines, 8 | and it displays across multiple lines''') 9 | 10 | print("This one-line string was written out \ 11 | using multiple lines") 12 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 4/Assignment solutions/4-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 4.2 review exercises 2 | 3 | 4 | # Display the number of letters in the string 5 | my_word = "antidisestablishmentarianism" 6 | print(len(my_word)) 7 | 8 | # Concatenate two strings together 9 | string_left = "bat" 10 | string_right = "man" 11 | print(string_left + string_right) 12 | 13 | # Display two strings together, with a space in between 14 | string_one = "heebie" 15 | string_two = "jeebies" 16 | print(string_one, string_two) 17 | 18 | 19 | # Use subscripting to display part of a string 20 | print("bazinga"[2:6]) 21 | 22 | 23 | # A more advanced way to do the above example would be: 24 | my_string = "bazinga" 25 | start_index = 2 26 | print(my_string[start_index:len(my_string)-start_index+1]) 27 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 4/Assignment solutions/4-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 4.3 review exercises 2 | 3 | # Take input from the user and display that input back 4 | my_input = input("Type something: ") 5 | print(my_input) 6 | 7 | # Display the input string converted to lower-case letters 8 | print(my_input.lower()) 9 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 4/Assignment solutions/first_letter.py: -------------------------------------------------------------------------------- 1 | # 4.3 first_letter.py 2 | # Return the upper-case first letter entered by the user 3 | 4 | user_input = input("Tell me your password: ") 5 | first_letter = user_input[0] 6 | print("The first letter you entered was:", first_letter.upper()) 7 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 5/Assignment solutions/5-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 5.1 review exercises 2 | 3 | 4 | # Store an integer as a string 5 | my_integer_string = "6" 6 | 7 | # Convert the 'integer' string into an int object using int() 8 | # Multiply the integer by 7 and display the result 9 | print(int(my_integer_string) * 7) 10 | 11 | 12 | # Store a floating-point number as a string 13 | my_float_string = "6.01" 14 | 15 | # Convert the 'float' string into a number using float() 16 | # Multiply the number by 7 and display the result 17 | print(float(my_float_string) * 7) 18 | 19 | 20 | # Create a string and an int object, then display them together 21 | my_string = "mp" 22 | my_int = 3 23 | print(my_string + str(my_int)) 24 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 5/Assignment solutions/5-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 5.2 review exercises 2 | 3 | weight = 0.2 4 | animal = "newt" 5 | 6 | # Concatenate a number and a string in one print statement 7 | print(str(weight) + " kg is the weight of the newt.") 8 | 9 | # Use format() to print a number and a string inside of another string 10 | print("{} kg is the weight of the {}.".format(weight, animal)) 11 | 12 | # Use format() to add objects inside a string using index numbers 13 | # (Here we reversed the arguments - just because we could.) 14 | print("{1} kg is the weight of the {0}.".format(animal, weight)) 15 | 16 | # Use format() to print new objects inside a string 17 | print("{} kg is the weight of the {}.".format(0.2, "newt")) 18 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 5/Assignment solutions/5-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 5.3 review exercises 2 | 3 | 4 | # Cannot find the string "a" in the string "AAA": 5 | print("AAA".find("a")) 6 | 7 | 8 | # Try to find a number inside a string; 9 | # use str() to convert the number first 10 | version = "version 2.0" 11 | v_num = 2.0 12 | print(version.find(str(v_num))) 13 | 14 | 15 | # Try to find an upper-case "X" in user input: 16 | my_input = input("Type something: ") 17 | print(my_input.find("X")) 18 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 5/Assignment solutions/translate.py: -------------------------------------------------------------------------------- 1 | # 5.3 translate.py 2 | # Turn a user's input into leetspeak 3 | 4 | my_text = input("Enter some text: ") 5 | 6 | my_text = my_text.replace("a", "4") 7 | my_text = my_text.replace("b", "8") 8 | my_text = my_text.replace("e", "3") 9 | my_text = my_text.replace("l", "1") 10 | my_text = my_text.replace("o", "0") 11 | my_text = my_text.replace("s", "5") 12 | my_text = my_text.replace("t", "7") 13 | 14 | print(my_text) 15 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 6/Assignment solutions/6-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 6.1 review exercises 2 | 3 | 4 | print(5 / 2) 5 | # This line will *not* perform "integer division" in Python 3 6 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 6/Assignment solutions/6-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 6.2 review exercises 2 | 3 | 4 | def cube(num): 5 | ''' Returns the cube of the input number ''' 6 | cube_num = num * num * num 7 | return cube_num 8 | 9 | print("0 cubed is", cube(0)) 10 | print("2 cubed is", cube(2)) 11 | 12 | 13 | def multiply(num1, num2): 14 | ''' Returns the result of multiplying two input numbers ''' 15 | return num1 * num2 16 | 17 | mult_result = multiply(2, 5) 18 | print("2 times 5 is", mult_result) 19 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 6/Assignment solutions/6-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 6.3 review exercises 2 | 3 | 4 | # print the integer 2 through 10 using a "for" loop 5 | for i in range(2, 11): 6 | print(i) 7 | 8 | 9 | # print the integer 2 through 10 using a "while" loop 10 | i = 2 11 | while (i < 11): 12 | print(i) 13 | i = i + 1 14 | 15 | 16 | def doubles(num): 17 | ''' Return the result of multiplying an input number by 2 ''' 18 | return num * 2 19 | 20 | # Call doubles to double the number 2 three times 21 | my_num = 2 22 | for i in range(0, 3): 23 | my_num = doubles(my_num) 24 | print(my_num) 25 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 6/Assignment solutions/exponent.py: -------------------------------------------------------------------------------- 1 | # 6.1 exponent.py 2 | # Receive two input numbers and calculate their power 3 | 4 | base = input("Enter a base: ") 5 | exponent = input("Enter an exponent: ") 6 | result = float(base) ** float(exponent) 7 | print("{} to the power of {} = {}".format(base, exponent, result)) 8 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 6/Assignment solutions/invest.py: -------------------------------------------------------------------------------- 1 | # 6.3 invest.py 2 | # calculate compound interest to track the growth of an investment 3 | 4 | 5 | def invest(amount, rate, time): 6 | print("principal amount: ${}".format(amount)) 7 | print("annual rate of return:", rate) 8 | for t in range(1, time + 1): 9 | amount = amount * (1 + rate) 10 | print("year {}: ${}".format(t, amount)) 11 | print() 12 | 13 | invest(100, .05, 8) 14 | invest(2000, .025, 5) 15 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 6/Assignment solutions/temperature.py: -------------------------------------------------------------------------------- 1 | # 6.2 temperature.py 2 | # Convert Celsius and Fahrenheit temperatures using functions 3 | 4 | 5 | def convert_cel_to_far(cel_temp): 6 | far_temp = cel_temp * 9/5 + 32 7 | return far_temp 8 | 9 | 10 | def convert_far_to_cel(far_temp): 11 | cel_temp = (far_temp - 32) * 5/9 12 | return cel_temp 13 | 14 | temp1 = 72 15 | print("{} degrees F = {} degrees C".format(temp1, convert_far_to_cel(temp1))) 16 | 17 | temp2 = 37 18 | print("{} degrees C = {} degrees F".format(temp2, convert_cel_to_far(temp2))) 19 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/8-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.1 review exercises 2 | 3 | 4 | # Test whether these expressions are True or False 5 | print(1 <= 1) 6 | print(1 != 1) 7 | print(1 != 2) 8 | print("good" != "bad") 9 | print("good" != "Good") 10 | print(123 == "123") 11 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/8-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.2 review exercises 2 | 3 | 4 | # Test whether these expressions are True or False 5 | print((1 <= 1) and (1 != 1)) 6 | print(not (1 != 2)) 7 | print(("good" != "bad") or False) 8 | print(("good" != "Good") and not (1 == 1)) 9 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/8-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.3 review exercises 2 | 3 | 4 | # Display whether the length of user input is <, > or = 5 characters 5 | my_input = input("Type something: ") 6 | 7 | if len(my_input) < 5: 8 | print("Your input is less than 5 characters long.") 9 | elif len(my_input) > 5: 10 | print("Your input is greater than 5 characters long.") 11 | else: 12 | print("Your input is 5 characters long.") 13 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/8-4 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.4 review exercises 2 | 3 | 4 | # Run in an infinite loop until the user types "q" or "Q" 5 | while True: 6 | my_input = input('Type "q" or "Q" to quit: ') 7 | if my_input.upper() == "Q": 8 | break 9 | 10 | # Display every number from 1 through 50 except multiples of 3 11 | for i in range(1, 51): 12 | if i % 3 == 0: 13 | continue 14 | print(i) 15 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/8-5 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.5 review exercises 2 | 3 | 4 | # Ask the user to enter an integer. 5 | # Repeat the process if the user hasn't entered an integer. 6 | repeat = True 7 | while repeat: 8 | try: 9 | my_input = input("Type an integer: ") 10 | print(int(my_input)) 11 | repeat = False 12 | except ValueError: 13 | print("try again") 14 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/8-6 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.6 review exercises 2 | 3 | from random import randint 4 | 5 | 6 | # Simulate the toss of a die 7 | print(randint(1, 6)) 8 | 9 | 10 | # Simulate 10,000 throws of dice and display the average result 11 | trials = 10000 12 | total = 0 13 | for trial in range(0, trials): 14 | total += randint(1, 6) 15 | avg_result = total / trials 16 | print("The average result of {} throws was {}".format(trials, avg_result)) 17 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/coin_toss.py: -------------------------------------------------------------------------------- 1 | # 8.6.2 coin_toss.py 2 | # Simulate the results of a series of coin tosses and track the results 3 | 4 | from random import randint 5 | 6 | flips = 0 7 | trials = 10000 8 | 9 | for trial in range(0, trials): 10 | flips += 1 # first flip 11 | if randint(0, 1) == 0: # flipped tails on first flip 12 | while randint(0, 1) == 0: # keep flipping tails 13 | flips += 1 14 | flips += 1 # finally flipped heads 15 | else: # otherwise, flipped heads on first flip 16 | while randint(0, 1) == 1: # keep flipping heads 17 | flips += 1 18 | flips += 1 # finally flipped tails 19 | 20 | print(flips / trials) 21 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/coin_toss_alternative.py: -------------------------------------------------------------------------------- 1 | # 8.6.2 coin_toss_alternative.py 2 | # Simulate the results of a series of coin tosses and track the results 3 | 4 | from random import randint 5 | 6 | 7 | trials = 100000 8 | flips = 0 9 | 10 | for trial in range(1, trials): 11 | first_flip = randint(0, 1) 12 | flips += 1 13 | while randint(0, 1) == first_flip: 14 | flips += 1 15 | flips += 1 16 | 17 | print("The average number of coin flips was {0}".format(flips/trials)) 18 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/election.py: -------------------------------------------------------------------------------- 1 | # 8.6.1 election.py 2 | # Simulate the results of an election using a Monte Carlo simulation 3 | 4 | from random import random 5 | 6 | total_A_wins = 0 7 | total_B_wins = 0 8 | 9 | trials = 100000 10 | for trial in range(0, trials): 11 | A_win = 0 12 | B_win = 0 13 | if random() < .87: # 1st region 14 | A_win += 1 15 | else: 16 | B_win += 1 17 | if random() < .65: # 2nd region 18 | A_win += 1 19 | else: 20 | B_win += 1 21 | if random() < .17: # 3rd region 22 | A_win += 1 23 | else: 24 | B_win += 1 25 | # determine overall election outcome 26 | if A_win > B_win: 27 | total_A_wins += 1 28 | else: 29 | total_B_wins += 1 30 | 31 | print("Probability A wins:", total_A_wins/trials) 32 | print("Probability B wins:", total_B_wins/trials) 33 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 8/Assignment solutions/factors.py: -------------------------------------------------------------------------------- 1 | # 8.3 factors.py 2 | # display all the factors of a number chosen by the user 3 | 4 | num = int(input("Enter a positive integer: ")) 5 | for divisor in range(1, num+1): 6 | if num % divisor == 0: 7 | print("{} is a divisor of {}".format(divisor, num)) 8 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 9/Assignment solutions/9-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 9.1 review exercises 2 | 3 | 4 | desserts = ["ice cream", "cookies"] 5 | 6 | # Sort the desserts list alphabetically 7 | desserts.sort() 8 | 9 | # Display the sorted list 10 | print(desserts) 11 | 12 | # Display the index value of "ice cream" 13 | print(desserts.index("ice cream")) 14 | 15 | # Copy the contents of the "desserts" list into a new "food" list 16 | food = desserts[:] 17 | 18 | # Add some food to the list 19 | food.append("broccoli") 20 | food.append("turnips") 21 | 22 | # Display the contents of both lists 23 | print(desserts) 24 | print(food) 25 | 26 | # Take "cookies" out of the "food" list 27 | food.remove("cookies") 28 | 29 | # Display the first two items in the "food" list 30 | print(food[0:2]) 31 | 32 | # Create a "breakfast" list full of cookies and display it 33 | my_breakfast = "cookies, cookies, cookies" 34 | breakfast = my_breakfast.split(", ") 35 | print(breakfast) 36 | 37 | """ 38 | Define a function that takes a list of numbers, `[2, 4, 8, 16, 32, 64]`, as the 39 | argument and then outputs only the numbers from the list that fall between 1 40 | and 20 (inclusive) 41 | """ 42 | 43 | 44 | def print_list(list_of_nums): 45 | for num in list_of_nums: 46 | if num >= 2 and num <= 20: 47 | print(num) 48 | 49 | list_of_numbers = [2, 4, 8, 16, 32, 64] 50 | print_list(list_of_numbers) 51 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 9/Assignment solutions/9-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 9.2 review exercises 2 | 3 | 4 | # Create a tuple "cardinal_nums" with "first", "second" and "third" 5 | cardinal_nums = ("first", "second", "third") 6 | 7 | # Display the second object in the tuple 8 | print(cardinal_nums[1]) 9 | 10 | 11 | # unpack the tuple into three string and display them 12 | pos1, pos2, pos3 = cardinal_nums 13 | print(pos1) 14 | print(pos2) 15 | print(pos3) 16 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 9/Assignment solutions/9-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 9.3 review exercises 2 | 3 | 4 | # Create an empty dictionary 5 | birthdays = {} 6 | 7 | # Add some key-value pairs to the dictionary 8 | birthdays["Luke Skywalker"] = "5/25/19" 9 | birthdays["Obi-Wan Kenobi"] = "3/11/57" 10 | birthdays["Darth Vader"] = "4/1/41" 11 | 12 | # Check if "Yoda" and "Darth Vader exist; if not, add them 13 | if not "Yoda" in birthdays: 14 | birthdays["Yoda"] = "unknown" 15 | if not "Darth Vader" in birthdays: 16 | birthdays["Darth Vader"] = "unknown" 17 | 18 | ## Bonus points: you could instead loop over a list of names to check 19 | #for name in ["Yoda", "Darth Vader"]: 20 | # if not name in birthdays: 21 | # birthdays[name] = "unknown" 22 | 23 | # Display the contents of the dictionary, one pair at a time 24 | for name in birthdays: 25 | print(name, birthdays[name]) 26 | 27 | # Remove "Darth Vader" 28 | del(birthdays["Darth Vader"]) 29 | print(birthdays) 30 | 31 | 32 | # Bonus: could have created dictionary by passing a list to dict() 33 | birthdays = dict([("Luke Skywalker", "5/25/19"), 34 | ("Obi-Wan Kenobi", "3/11/57"), 35 | ("Darth Vader", "4/1/41")]) 36 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 9/Assignment solutions/capital_city_loop.py: -------------------------------------------------------------------------------- 1 | from capitals import capitals_dict 2 | import random 3 | 4 | 5 | def capital_game(state, capital): 6 | while True: 7 | guess = input("What is the capital of '{}'? ".format(state)).lower() 8 | if guess == "exit": 9 | print("The capital of '{}' is '{}'.".format(state, capital)) 10 | print("Goodbye") 11 | break 12 | elif guess == (capital).lower(): 13 | print("Correct! Nice job.") 14 | break 15 | 16 | 17 | state = random.choice(list(capitals_dict.keys())) 18 | capital = capitals_dict[state] 19 | capital_game(state, capital) 20 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 9/Assignment solutions/capitals.py: -------------------------------------------------------------------------------- 1 | capitals_dict = { 2 | 'Alabama': 'Montgomery', 3 | 'Alaska': 'Juneau', 4 | 'Arizona': 'Phoenix', 5 | 'Arkansas': 'Little Rock', 6 | 'California': 'Sacramento', 7 | 'Colorado': 'Denver', 8 | 'Connecticut': 'Hartford', 9 | 'Delaware': 'Dover', 10 | 'Florida': 'Tallahassee', 11 | 'Georgia': 'Atlanta', 12 | 'Hawaii': 'Honolulu', 13 | 'Idaho': 'Boise', 14 | 'Illinois': 'Springfield', 15 | 'Indiana': 'Indianapolis', 16 | 'Iowa': 'Des Moines', 17 | 'Kansas': 'Topeka', 18 | 'Kentucky': 'Frankfort', 19 | 'Louisiana': 'Baton Rouge', 20 | 'Maine': 'Augusta', 21 | 'Maryland': 'Annapolis', 22 | 'Massachusetts': 'Boston', 23 | 'Michigan': 'Lansing', 24 | 'Minnesota': 'Saint Paul', 25 | 'Mississippi': 'Jackson', 26 | 'Missouri': 'Jefferson City', 27 | 'Montana': 'Helena', 28 | 'Nebraska': 'Lincoln', 29 | 'Nevada': 'Carson City', 30 | 'New Hampshire': 'Concord', 31 | 'New Jersey': 'Trenton', 32 | 'New Mexico': 'Santa Fe', 33 | 'New York': 'Albany', 34 | 'North Carolina': 'Raleigh', 35 | 'North Dakota': 'Bismarck', 36 | 'Ohio': 'Columbus', 37 | 'Oklahoma': 'Oklahoma City', 38 | 'Oregon': 'Salem', 39 | 'Pennsylvania': 'Harrisburg', 40 | 'Rhode Island': 'Providence', 41 | 'South Carolina': 'Columbia', 42 | 'South Dakota': 'Pierre', 43 | 'Tennessee': 'Nashville', 44 | 'Texas': 'Austin', 45 | 'Utah': 'Salt Lake City', 46 | 'Vermont': 'Montpelier', 47 | 'Virginia': 'Richmond', 48 | 'Washington': 'Olympia', 49 | 'West Virginia': 'Charleston', 50 | 'Wisconsin': 'Madison', 51 | 'Wyoming': 'Cheyenne', 52 | } 53 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 9/Assignment solutions/cats_with_hats.py: -------------------------------------------------------------------------------- 1 | def get_cats_with_hats(array_of_cats): 2 | cats_with_hats_on = [] 3 | for num in range(1, 100+1): 4 | for cat in range(1, 100+1): 5 | if cat % num == 0: 6 | if array_of_cats[cat] is True: 7 | array_of_cats[cat] = False 8 | else: 9 | array_of_cats[cat] = True 10 | for cat in range(1, 100+1): 11 | if cats[cat] is True: 12 | cats_with_hats_on.append(cat) 13 | return cats_with_hats_on 14 | 15 | cats = [False] * (100+1) 16 | print(get_cats_with_hats(cats)) 17 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 9/Assignment solutions/cats_with_hats_alternative.py: -------------------------------------------------------------------------------- 1 | number_of_cats = 100 2 | cats_with_hats = [] 3 | number_of_laps = 100 4 | 5 | # We want the laps to be from 1 to 100 instead of 0 to 99 6 | for lap in range(1, number_of_laps + 1): 7 | for cat in range(1, number_of_cats + 1): 8 | 9 | # Only look at cats that are divisible by the lap 10 | if cat % lap == 0: 11 | if cat in cats_with_hats: 12 | cats_with_hats.remove(cat) 13 | else: 14 | cats_with_hats.append(cat) 15 | 16 | print(cats_with_hats) 17 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/Chapter 9/Assignment solutions/cats_with_hats_dict.py: -------------------------------------------------------------------------------- 1 | theCats = {} 2 | 3 | for i in range(1, 101): 4 | theCats[i] = False 5 | 6 | for i in range(1, 101): 7 | for cats, hats in theCats.items(): 8 | if cats % i == 0: 9 | if theCats[cats]: 10 | theCats[cats] = False 11 | else: 12 | theCats[cats] = True 13 | 14 | for cats, hats in theCats.items(): 15 | if theCats[cats]: 16 | print("Cat {} has a hat.".format(cats)) 17 | else: 18 | print("Cat {} is hatless!".format(cats)) 19 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/oop/dog_class.py: -------------------------------------------------------------------------------- 1 | class Dog(): 2 | 3 | # Class Attribute 4 | species = 'mammal' 5 | 6 | # Initializer / Instance Attributes 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | 12 | # Instantiate the Dog object 13 | philo = Dog("Philo", 5) 14 | mikey = Dog("Mikey", 6) 15 | 16 | # Access the instance attributes 17 | print("{} is {} and {} is {}.".format( 18 | philo.name, philo.age, mikey.name, mikey.age)) 19 | 20 | # Is Philo a mammal? 21 | if philo.species == "mammal": 22 | print("{0} is a {1}!".format(philo.name, philo.species)) 23 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/oop/dog_inheritence.py: -------------------------------------------------------------------------------- 1 | # Parent class 2 | class Dog(): 3 | 4 | # Class attribute 5 | species = 'mammal' 6 | 7 | # Initializer / Instance attributes 8 | def __init__(self, name, age): 9 | self.name = name 10 | self.age = age 11 | 12 | # instance method 13 | def description(self): 14 | return self.name, self.age 15 | 16 | # instance method 17 | def speak(self, sound): 18 | return "%s says %s" % (self.name, sound) 19 | 20 | 21 | # child class (inherits from Dog() class) 22 | class RussellTerrier(Dog): 23 | def run(self, speed): 24 | return "%s runs %s" % (self.name, speed) 25 | 26 | 27 | # child class (inherits from Dog() class) 28 | class Bulldog(Dog): 29 | def run(self, speed): 30 | return "%s runs %s" % (self.name, speed) 31 | 32 | 33 | # child classes inherit attributes and 34 | # behaviors from the parent class 35 | jim = Bulldog("Jim", 12) 36 | print(jim.description()) 37 | 38 | # child classes have specific attributes 39 | # and behaviors as well 40 | print(jim.run("slow")) 41 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/oop/dog_instance_methods.py: -------------------------------------------------------------------------------- 1 | class Dog(): 2 | 3 | # Class Attribute 4 | species = 'mammal' 5 | 6 | # Initializer / Instance Attributes 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | # instance method 12 | def description(self): 13 | return self.name, self.age 14 | 15 | # instance method 16 | def speak(self, sound): 17 | return "%s says %s" % (self.name, sound) 18 | 19 | # Instantiate the Dog object 20 | mikey = Dog("Mikey", 6) 21 | 22 | # call our instance methods 23 | print(mikey.description()) 24 | print(mikey.speak("Gruff Gruff")) 25 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/oop/dog_isinstance.py: -------------------------------------------------------------------------------- 1 | # Parent class 2 | class Dog(): 3 | 4 | # Class attribute 5 | species = 'mammal' 6 | 7 | # Initializer / Instance attributes 8 | def __init__(self, name, age): 9 | self.name = name 10 | self.age = age 11 | 12 | # instance method 13 | def description(self): 14 | return self.name, self.age 15 | 16 | # instance method 17 | def speak(self, sound): 18 | return "%s says %s" % (self.name, sound) 19 | 20 | 21 | # child class (inherits from Dog() class) 22 | class RussellTerrier(Dog): 23 | def run(self, speed): 24 | return "%s runs %s" % (self.name, speed) 25 | 26 | 27 | # child class (inherits from Dog() class) 28 | class Bulldog(Dog): 29 | def run(self, speed): 30 | return "%s runs %s" % (self.name, speed) 31 | 32 | 33 | # child classes inherit attributes and 34 | # behaviors from the parent class 35 | jim = Bulldog("Jim", 12) 36 | print(jim.description()) 37 | 38 | # child classes have specific attributes 39 | # and behaviors as well 40 | print(jim.run("slow")) 41 | 42 | # is jim an instance of Dog()? 43 | print(isinstance(jim, Dog)) 44 | 45 | # is julie an instance of Dog()? 46 | julie = Dog("Julie", 100) 47 | print(isinstance(julie, Dog)) 48 | 49 | # is johnny walker an instance of Bulldog() 50 | johnnywalker = RussellTerrier("Johnny Walker", 4) 51 | print(isinstance(johnnywalker, Bulldog)) 52 | 53 | # is julie and instance of jim? 54 | print(isinstance(julie, jim)) 55 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/oop/dog_walking.py: -------------------------------------------------------------------------------- 1 | # parent class 2 | class Pet(): 3 | 4 | dogs = [] 5 | 6 | def __init__(self, dogs): 7 | self.dogs = dogs 8 | 9 | def walk(self): 10 | for dog in self.dogs: 11 | print(dog.walk()) 12 | 13 | 14 | # parent class 15 | class Dog(): 16 | 17 | # class attribute 18 | species = 'mammal' 19 | is_hungry = True 20 | 21 | # initializer / instance attributes 22 | def __init__(self, name, age): 23 | self.name = name 24 | self.age = age 25 | 26 | # instance method 27 | def description(self): 28 | return self.name, self.age 29 | 30 | # instance method 31 | def speak(self, sound): 32 | return "%s says %s" % (self.name, sound) 33 | 34 | # instance method 35 | def eat(self): 36 | self.is_hungry = False 37 | 38 | def walk(self): 39 | return "%s is walking!" % (self.name) 40 | 41 | 42 | # child class (inherits from Dog() class) 43 | class RussellTerrier(Dog): 44 | def run(self, speed): 45 | return "%s runs %s" % (self.name, speed) 46 | 47 | 48 | # child class (inherits from Dog() class) 49 | class Bulldog(Dog): 50 | def run(self, speed): 51 | return "%s runs %s" % (self.name, speed) 52 | 53 | # create instances of dogs 54 | my_dogs = [Bulldog("Tom", 6), RussellTerrier("Fletcher", 7), Dog("Larry", 9)] 55 | 56 | # instantiate the Pet() class 57 | my_pets = Pet(my_dogs) 58 | 59 | # output 60 | my_pets.walk() 61 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/oop/github_with_class.py: -------------------------------------------------------------------------------- 1 | from urllib.request import Request, urlopen 2 | 3 | 4 | class Github(object): 5 | 6 | def __init__(self, username): 7 | self.username = username 8 | self.base_url = 'https://api.github.com/users/' 9 | 10 | def get_user_info(self): 11 | full_url = "{0}{1}".format(self.base_url, self.username) 12 | request = Request(full_url) 13 | handler = urlopen(request) 14 | if handler.getcode() == 200: 15 | return handler.read() 16 | 17 | def get_user_repos(self): 18 | full_url = "{0}{1}/repos".format(self.base_url, self.username) 19 | request = Request(full_url) 20 | handler = urlopen(request) 21 | if handler.getcode() == 200: 22 | return handler.read() 23 | 24 | 25 | user = Github('mjhea0') 26 | print(user.get_user_info()) 27 | print(user.get_user_repos()) 28 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/oop/oldest_dog.py: -------------------------------------------------------------------------------- 1 | class Dog(): 2 | 3 | # Class Attribute 4 | species = 'mammal' 5 | 6 | # Initializer / Instance Attributes 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | 12 | # Instantiate the Dog object 13 | jake = Dog("Jake", 7) 14 | doug = Dog("Doug", 4) 15 | william = Dog("William", 5) 16 | 17 | 18 | # Determine the oldest dog 19 | def get_biggest_number(*args): 20 | return max(args) 21 | 22 | # output 23 | print("The oldest dog is {} years old.".format( 24 | get_biggest_number(jake.age, doug.age, william.age))) 25 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/oop/pet_class.py: -------------------------------------------------------------------------------- 1 | # parent class 2 | class Pet(): 3 | 4 | dogs = [] 5 | 6 | def __init__(self, dogs): 7 | self.dogs = dogs 8 | 9 | 10 | # parent class 11 | class Dog(): 12 | 13 | # class attribute 14 | species = 'mammal' 15 | is_hungry = True 16 | 17 | # initializer / Instance attributes 18 | def __init__(self, name, age): 19 | self.name = name 20 | self.age = age 21 | 22 | # instance method 23 | def description(self): 24 | return self.name, self.age 25 | 26 | # instance method 27 | def speak(self, sound): 28 | return "%s says %s" % (self.name, sound) 29 | 30 | # instance method 31 | def eat(self): 32 | self.is_hungry = False 33 | 34 | 35 | # child class (inherits from Dog() class) 36 | class RussellTerrier(Dog): 37 | def run(self, speed): 38 | return "%s runs %s" % (self.name, speed) 39 | 40 | 41 | # child class (inherits from Dog() class) 42 | class Bulldog(Dog): 43 | def run(self, speed): 44 | return "%s runs %s" % (self.name, speed) 45 | 46 | # create instances of dogs 47 | my_dogs = [Bulldog("Tom", 6), RussellTerrier("Fletcher", 7), Dog("Larry", 9)] 48 | 49 | # instantiate the Pet() class 50 | my_pets = Pet(my_dogs) 51 | 52 | # output 53 | print("I have {} dogs.".format(len(my_pets.dogs))), 54 | for dog in my_pets.dogs: 55 | dog.eat() 56 | print("{} is {}.".format(dog.name, dog.age)), 57 | print("And they're all {}s, of course.".format(dog.species)), 58 | if dog.is_hungry is True: 59 | print("My dogs are hungry.") 60 | else: 61 | print("My dogs are not hungry.") 62 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/regular_expressions/phone-book-fun.py: -------------------------------------------------------------------------------- 1 | import re 2 | from phone_list import data 3 | 4 | 5 | def parse_phone_book(phone_book): 6 | for line in phone_book: 7 | if re.search(r'K.*Hardy', line['name']): 8 | print("{} - {}".format(line['name'], line["phone"])) 9 | 10 | parse_phone_book(data) 11 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/regular_expressions/regex-groups.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | string = "My name is Michael Herman" 4 | 5 | # re.match(pattern, string, flags=0) 6 | m = re.match(r'(.*) name (.[s]?) .*', string) 7 | # m = re.match(r'(.*) name .[s]? (.*)', string) # what does this do? 8 | 9 | if m: 10 | print("group(0): ", m.group(0)) 11 | print("group(1): ", m.group(1)) 12 | print("group(2): ", m.group(2)) 13 | else: 14 | print("Sorry. No match!!") 15 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/regular_expressions/regex-namedgroups.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | string = "Michael Herman" 4 | 5 | # re.match(pattern, string, flags=0) 6 | m = re.match(r"(?P\w+)\W+(?P\w+)", string) 7 | 8 | if m: 9 | print("group(0) : ", m.group(0)) 10 | print("group(1) : ", m.group(1)) 11 | print("group(2) : ", m.group(2)) 12 | print("") 13 | print('group("first") : ', m.group("first")) 14 | print('group("last") : ', m.group("last")) 15 | else: 16 | print("Sorry. No match!!") 17 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/regular_expressions/regex-validation-refactor.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | validation = re.compile(r'[A-Za-z0-9.]+@[A-Za-z0-9.]+.com$') 4 | 5 | email = input("Please enter your email address: ") 6 | 7 | while not validation.search(email): 8 | print("Please enter your email address correctly!") 9 | email = input("Please enter your email address: ") 10 | 11 | print("\nYour email address is {}!".format(email)) 12 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/regular_expressions/regex-validation.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | validation = re.compile(r'[A-Za-zs.]') 4 | 5 | name = input("Please enter your name: ") 6 | 7 | while not validation.search(name): 8 | print("Please enter your name correctly!") 9 | name = input("Please enter your name: ") 10 | 11 | print("\nYour name is {}!".format(name)) 12 | -------------------------------------------------------------------------------- /_old/Course materials - Python 3/regular_expressions/regex_answers.txt: -------------------------------------------------------------------------------- 1 | 1. Blank lines - ^\s*\n 2 | 1. Spaces from the beginning of each line - ^\s+ 3 | 1. Bracketed numbers (e.g., '[1]') - \[\d+\] 4 | 1. The first column of numbers - ^\d+\s+ 5 | 1. 'Inc.', ', Inc.', 'Inc', and 'Incorporated' - (,* |,)(Incorporated|Inc\.*) 6 | 1. Space between the area code, '(XXX)', and the phone number, 'XXX-XXXX' - find - (\(\d{3}\))(\s)(\d{3}-\d{4}) then replace - $1$3 -------------------------------------------------------------------------------- /_old/Course materials - Python 3/regular_expressions/regex_review.py: -------------------------------------------------------------------------------- 1 | # Modify the variable value so that all of the `print` statements return `True`. 2 | 3 | import re 4 | 5 | zero = "Python" 6 | one = "5/25/2014" 7 | two = "A88 8AA" 8 | three = '\w\d\w\s\w\d\w' 9 | four = "$4.76" 10 | five = ["haaaappy", "birthday"] 11 | six = r'\.(doc|odt)$' 12 | seven = "My email is (email redacted)" 13 | 14 | # zero = "Ruby" 15 | # one = "5/25/14" 16 | # two = "A99 9AA" 17 | # three = r'' 18 | # four = "6.76" 19 | # five = ["happy","birthday"] 20 | # six = r'\.(doc)$' 21 | # seven = "My email is michael@mherman.org" 22 | 23 | # DO NOT CHANGE ANYTHING BELOW THIS LINE # 24 | # -------------------------------------- # 25 | 26 | print("zero: {}".format( 27 | zero == re.search(r'[P].*', "This is Real Python").group()) 28 | ) 29 | print("one: {}".format( 30 | one == re.search(r'\d{1,2}\/\d{1,2}\/\d{4}', "5/25/2014").group()) 31 | ) 32 | print("two: {}".format( 33 | two == re.match( 34 | r'[A-Z]([A-Z](\d{1,2}|\d[A-Z])|\d{1,2})\s\d[A-Z]{2}', 35 | "A88 8AA", 36 | re.VERBOSE 37 | ).group() 38 | )) 39 | print("three: {}".format(bool(re.search(three, "B4c r79").group()))) 40 | print("four: {}".format(bool(re.search(r'\$[0-5]\.\d\d', four)))) 41 | print("five: {}".format(bool(re.search(r'\ha{4,10}ppy\b', five[0])))) 42 | files = ['test.doc', 'test.odt', 'test.ddt', 'doc', 'testodt', 'test.doc'] 43 | matched_files = [file for file in files if re.search(six, file)] 44 | print("six: {}".format(len(matched_files) == 3)) 45 | email_regex = r'\w+@\w+\.(com|org|edu|net)' 46 | text = "My email is michael@mherman.org" 47 | redacted_text = re.sub(email_regex, '(email redacted)', text) 48 | print("seven: {}".format(seven == redacted_text)) 49 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Assignment solutions/10-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 10.1 review exercises 2 | 3 | 4 | ''' 5 | In order to run correctly, this script first needs to 6 | be placed in the Chapter 10 "Practice files" folder. 7 | (File paths are covered in section 10.2) 8 | ''' 9 | 10 | # Read a text file by looping over individual lines 11 | my_poem = open("poem.txt", "r") 12 | for line in my_poem.readlines(): 13 | # Use a comma after the print statement; 14 | # file already contains newline characters 15 | print line, 16 | my_poem.close() 17 | 18 | # Print some blank lines to separate the two examples 19 | print "\n\n" 20 | 21 | # Use "with" to automatically close a file when finished 22 | with open("poem.txt", "r") as my_poem: 23 | for line in my_poem.readlines(): 24 | print line, 25 | 26 | # Write the contents of one file into another, line-by-line 27 | poem_in = open("poem.txt", "r") 28 | poem_out = open("output.txt", "w") 29 | for line in poem_in.readlines(): 30 | poem_out.write(line) 31 | poem_in.close() 32 | poem_out.close() 33 | 34 | # Repeat the previous exercise using the "with" keyword 35 | # (This will overwrite the previous output file.) 36 | with open("poem.txt", "r") as poem_in, open("output.txt", "w") as poem_out: 37 | for line in poem_in.readlines(): 38 | poem_out.write(line) 39 | 40 | 41 | # Append a new line to the end of "output.txt" 42 | # (Need to start on a new line, so add "\n" to the beginning.) 43 | with open("output.txt", "a") as poem_append: 44 | poem_append.write("\nThus ends the haiku.") 45 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Assignment solutions/10-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 10.2 review exercises 2 | 3 | 4 | # Initial setup 5 | import os 6 | import glob 7 | # This path may need to be changed depending on your setup 8 | path = "C:/Real Python/Course Materials/Chapter 10/Practice files/images" 9 | 10 | 11 | # Display the full paths of all files and folders in the main "images" folder 12 | print 'Full contents of "images" folder:' 13 | for file_name in os.listdir(path): 14 | print os.path.join(path, file_name) 15 | 16 | # Display the full paths of any PNG files in the "images" folder 17 | file_matches = os.path.join(path, "*.png") 18 | print 'All PNG files in "images" folder:' 19 | for file_name in glob.glob(file_matches): 20 | print file_name 21 | 22 | # Change all PNGs to JPGs in the "images" folder and its subfolders 23 | # Could use indexing to get the file extension, but try using os.path.splitext() 24 | for current_folder, subfolders, file_names in os.walk(path): 25 | for file_name in file_names: 26 | file_path = os.path.join(current_folder, file_name) 27 | file_tuple = os.path.splitext(file_path) # split into (path, extension) 28 | if file_tuple[1].lower() == ".png": # check if extension is PNG 29 | os.rename(file_path, file_tuple[0] + ".jpg") 30 | 31 | # Check that the two files have been converted to JPGs successfully 32 | print os.path.exists(os.path.join(path, "png file - not a gif.jpg")) 33 | print os.path.exists(os.path.join(path, "additional files/one last image.jpg")) 34 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Assignment solutions/10-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 10.3 review exercises 2 | 3 | 4 | # Initial setup 5 | import os 6 | import csv 7 | # This path may need to be changed depending on your setup 8 | path = "C:/Real Python/Course Materials/Chapter 10/Practice files" 9 | 10 | 11 | # Read in a CSV and display each row except the header row 12 | # Append a third column and write out the resulting CSV with a new header 13 | in_file_path = os.path.join(path, "pastimes.csv") 14 | out_file_path = os.path.join(path, "Output/categorized pastimes.csv") 15 | with open(in_file_path, "rb") as in_file, open(out_file_path, "wb") as out_file: 16 | csv_reader = csv.reader(in_file) 17 | csv_writer = csv.writer(out_file) 18 | 19 | # skip header row and write a new output header row 20 | csv_reader.next() 21 | csv_writer.writerow(["Name", "Favorite Pastime", "Type of pastime"]) 22 | 23 | for row in csv_reader: 24 | print row 25 | # Check if "Favorite Pastime" includes "fighting" 26 | if row[1].lower().find("fighting") != -1: 27 | row.append("Combat") 28 | else: 29 | row.append("Other") 30 | # Add the new row to the output 31 | csv_writer.writerow(row) 32 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Assignment solutions/high_scores.py: -------------------------------------------------------------------------------- 1 | # 10.3 high_scores.py 2 | # Read in CSV data containing names and scores; display a high score list 3 | 4 | import csv 5 | import os 6 | my_path = "C:/Real Python/Course materials/Chapter 10/Practice files" 7 | 8 | high_scores_dict = {} 9 | with open(os.path.join(my_path, "scores.csv"), "rb") as myFile: 10 | my_file_reader = csv.reader(myFile) 11 | for name, score in my_file_reader: # get each name/score pair 12 | score = int(score) # convert string score to integer 13 | if name in high_scores_dict: # already had an entry for that name 14 | if score > high_scores_dict[name]: # new score is higher 15 | high_scores_dict[name] = score 16 | else: # haven't seen this name yet; add it to dictionary 17 | high_scores_dict[name] = score 18 | 19 | for name in sorted(high_scores_dict): 20 | print name, high_scores_dict[name] 21 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Assignment solutions/remove_files.py: -------------------------------------------------------------------------------- 1 | # 10.2 remove_files.py 2 | # Remove JPG files from multiple folders based on file size 3 | 4 | import os 5 | 6 | path = "C:/Real Python/Course materials/Chapter 10/Practice files/little pics" 7 | for current_folder, subfolders, file_names in os.walk(path): 8 | for file_name in file_names: 9 | full_path = os.path.join(current_folder, file_name) 10 | # check if file is a JPG 11 | check_JPG = file_name.lower().endswith(".jpg") 12 | # check if size is less than 2Kb 13 | check_size = os.path.getsize(full_path) < 2000 14 | if check_JPG and check_size: # both conditions must be True 15 | print 'Deleting "{}"...'.format(file_name) 16 | os.remove(full_path) 17 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/backup/images/additional files/one last image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/backup/images/additional files/one last image.png -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/backup/images/an image file.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/backup/images/an image file.gif -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/backup/images/another image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/backup/images/another image.gif -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/backup/images/one more image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/backup/images/one more image.gif -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/backup/images/png file - not a gif.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/backup/images/png file - not a gif.png -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/backup/little pics/better not delete me.txt: -------------------------------------------------------------------------------- 1 | hi mom -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/backup/little pics/look in here too/definitely has to go.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/backup/little pics/look in here too/definitely has to go.jpg -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/backup/little pics/save me please.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/backup/little pics/save me please.jpg -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/backup/little pics/to be deleted.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/backup/little pics/to be deleted.jpg -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/example.txt: -------------------------------------------------------------------------------- 1 | Hi there. 2 | This is a simple text file. 3 | If you can read me, congratulations! -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/images/additional files/one last image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/images/additional files/one last image.png -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/images/an image file.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/images/an image file.gif -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/images/another image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/images/another image.gif -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/images/one more image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/images/one more image.gif -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/images/png file - not a gif.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/images/png file - not a gif.png -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/little pics/better not delete me.txt: -------------------------------------------------------------------------------- 1 | hi mom -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/little pics/look in here too/definitely has to go.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/little pics/look in here too/definitely has to go.jpg -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/little pics/save me please.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/little pics/save me please.jpg -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/little pics/to be deleted.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 10/Practice files/little pics/to be deleted.jpg -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/output.txt: -------------------------------------------------------------------------------- 1 | This is the first line 2 | The second line is longer 3 | Hippopotamus 4 | Thus ends the haiku. -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/pastimes.csv: -------------------------------------------------------------------------------- 1 | Person,Favorite pastime 2 | Fezzik,Fighting 3 | Westley,Winning 4 | Inigo Montoya,Sword fighting 5 | Buttercup,Complaining 6 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/poem.txt: -------------------------------------------------------------------------------- 1 | This is the first line 2 | The second line is longer 3 | Hippopotamus -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/scores.csv: -------------------------------------------------------------------------------- 1 | LLCoolDave,23 2 | LLCoolDave,27 3 | red,12 4 | LLCoolDave,26 5 | tom123,26 6 | O_O,7 7 | Misha46,24 8 | O_O,14 9 | Empiro,18 10 | Empiro,18 11 | MaxxT,25 12 | L33tH4x,42 13 | Misha46,25 14 | johnsmith,30 15 | Empiro,23 16 | O_O,22 17 | MaxxT,25 18 | Misha46,24 19 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/tabbed wonka.csv: -------------------------------------------------------------------------------- 1 | First name Last name Reward 2 | Charlie Bucket golden ticket, chocolate factory 3 | Veruca Salt squirrel revolution 4 | Violet Beauregarde fruit chew 5 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 10/Practice files/wonka.csv: -------------------------------------------------------------------------------- 1 | First name,Last name,Reward 2 | Charlie,Bucket,"golden ticket, chocolate factory" 3 | Veruca,Salt,squirrel revolution 4 | Violet,Beauregarde,fruit chew 5 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Assignment solutions/12-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 12.1 review exercises 2 | 3 | 4 | import os 5 | from pyPdf import PdfFileReader, PdfFileWriter 6 | 7 | path = "C:/Real Python/Course materials/Chapter 12/Practice files" 8 | input_file_name = os.path.join(path, "The Whistling Gypsy.pdf") 9 | input_file = PdfFileReader(file(input_file_name, "rb")) 10 | 11 | # Display meta-data about file 12 | print "Title:", input_file.getDocumentInfo().title 13 | print "Author:", input_file.getDocumentInfo().author 14 | print "Number of pages:", input_file.getNumPages() 15 | 16 | # Specify and open output text file 17 | output_file_name = os.path.join(path, "Output/The Whistling Gypsy.txt") 18 | with open(output_file_name, "w") as output_file: 19 | # Extract every page of text 20 | for page_num in range(0, input_file.getNumPages()): 21 | text = input_file.getPage(page_num).extractText() 22 | text = text.encode("utf-8") # convert text to unicode 23 | output_file.write(text) 24 | 25 | # Save file without cover page 26 | output_PDF = PdfFileWriter() 27 | for page_num in range(1, input_file.getNumPages()): 28 | output_PDF.addPage(input_file.getPage(page_num)) 29 | 30 | output_file_name = os.path.join(path, "Output/The Whistling Gypsy un-covered.pdf") 31 | with file(output_file_name, "wb") as output_file: 32 | output_PDF.write(output_file) 33 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Assignment solutions/12-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 12.2 review exercises 2 | 3 | import os 4 | import copy 5 | from pyPdf import PdfFileReader, PdfFileWriter 6 | 7 | path = "C:/Real Python/Course materials/Chapter 12/Practice files" 8 | input_file_name = os.path.join(path, "Walrus.pdf") 9 | input_file = PdfFileReader(file(input_file_name, "rb")) 10 | output_PDF = PdfFileWriter() 11 | 12 | input_file.decrypt("IamtheWalrus") # decrypt the input file 13 | 14 | for page_num in range(0, input_file.getNumPages()): 15 | # rotate pages (call everything page_left for now; will make a copy) 16 | page_left = input_file.getPage(page_num) 17 | page_left.rotateCounterClockwise(90) 18 | 19 | page_right = copy.copy(page_left) # split each page in half 20 | upper_right = page_left.mediaBox.upperRight # get original page corner 21 | 22 | # crop and add left-side page 23 | page_left.mediaBox.upperRight = (upper_right[0]/2, upper_right[1]) 24 | output_PDF.addPage(page_left) 25 | # crop and add right-side page 26 | page_right.mediaBox.upperLeft = (upper_right[0]/2, upper_right[1]) 27 | output_PDF.addPage(page_right) 28 | 29 | # save new pages to an output file 30 | output_file_name = os.path.join(path, "Output/Updated Walrus.pdf") 31 | with file(output_file_name, "wb") as output_file: 32 | output_PDF.write(output_file) 33 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Assignment solutions/cover_the_emperor.py: -------------------------------------------------------------------------------- 1 | # 12.2 cover_the_emperor.py 2 | # Add a cover sheet to a PDF; save the full output as a new PDF 3 | 4 | import os 5 | from pyPdf import PdfFileReader, PdfFileWriter 6 | 7 | path = "C:/Real Python/Course materials/Chapter 12/Practice files" 8 | input_file_name1 = os.path.join(path, "Emperor cover sheet.pdf") 9 | input_file1 = PdfFileReader(file(input_file_name1, "rb")) 10 | input_file_name2 = os.path.join(path, "The Emperor.pdf") 11 | input_file2 = PdfFileReader(file(input_file_name2, "rb")) 12 | output_PDF = PdfFileWriter() 13 | 14 | # Read in all pages from the cover sheet PDF file 15 | for page_num in range(0, input_file1.getNumPages()): 16 | page = input_file1.getPage(page_num) 17 | output_PDF.addPage(page) 18 | 19 | # Read in all pages from "The Emperor.pdf" into the same output file 20 | for page_num in range(0, input_file2.getNumPages()): 21 | page = input_file2.getPage(page_num) 22 | output_PDF.addPage(page) 23 | 24 | # Output the results into a new PDF 25 | output_file_name = os.path.join(path, "Output/The Covered Emperor.pdf") 26 | output_file = file(output_file_name, "wb") 27 | output_PDF.write(output_file) 28 | output_file.close() 29 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Practice files/Emperor cover sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/Practice files/Emperor cover sheet.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Practice files/Pride and Prejudice.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/Practice files/Pride and Prejudice.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Practice files/The Emperor.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/Practice files/The Emperor.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Practice files/The Whistling Gypsy.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/Practice files/The Whistling Gypsy.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Practice files/Walrus.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/Practice files/Walrus.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Practice files/half and half.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/Practice files/half and half.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Practice files/top secret.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/Practice files/top secret.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/Practice files/ugly.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/Practice files/ugly.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/basic_pdf.py: -------------------------------------------------------------------------------- 1 | from reportlab.pdfgen import canvas 2 | 3 | c = canvas.Canvas("hello.pdf") 4 | # c.drawString(100,100, "Hello World") 5 | c.drawString(250, 500, "Hello World") 6 | c.save() 7 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/hello.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/hello.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/hello_again.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/hello_again.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/less_basic_pdf.py: -------------------------------------------------------------------------------- 1 | from reportlab.pdfgen import canvas 2 | from reportlab.lib.pagesizes import letter 3 | from reportlab.lib.units import inch 4 | 5 | xmargin = 3.2*inch 6 | ymargin = 6*inch 7 | 8 | c = canvas.Canvas("hello_again.pdf", pagesize=letter) 9 | 10 | c.setLineWidth(1) 11 | c.drawString(xmargin, ymargin, "Hello World from ReportLab!") 12 | 13 | c.save() 14 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/table_pdf.py: -------------------------------------------------------------------------------- 1 | from reportlab.pdfgen import canvas 2 | from reportlab.lib.pagesizes import letter 3 | from reportlab.lib.units import inch 4 | from reportlab.lib import colors 5 | from reportlab.platypus import Table 6 | 7 | 8 | xmargin = 3.2*inch 9 | ymargin = 6*inch 10 | 11 | c = canvas.Canvas("tps_report.pdf", pagesize=letter) 12 | c.setFont('Helvetica', 12) 13 | 14 | 15 | data = [['#1', '#2', '#3', '#4', '#5'], 16 | ['10', '11', '12', '13', '14'], 17 | ['20', '21', '22', '23', '24'], 18 | ['30', '31', '32', '33', '34'], 19 | ['20', '21', '22', '23', '24'], 20 | ['20', '21', '22', '23', '24'], 21 | ['20', '21', '22', '23', '24'], 22 | ['20', '21', '22', '23', '24']] 23 | 24 | 25 | t = Table(data) 26 | t.setStyle([('TEXTCOLOR', (0, 0), (4, 0), colors.red)]) 27 | t.wrapOn(c, xmargin, ymargin) 28 | t.drawOn(c, xmargin, ymargin) 29 | c.save() 30 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 12/tps_report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/_old/Course materials/Chapter 12/tps_report.pdf -------------------------------------------------------------------------------- /_old/Course materials/Chapter 13/Assignment solutions/13-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 13.1 review exercises 2 | 3 | import sqlite3 4 | 5 | # Create a temporary database connection in RAM 6 | with sqlite3.connect(':memory:') as connection: 7 | c = connection.cursor() 8 | 9 | # Create a "Roster" table with Name, Species and IQ fields 10 | c.execute("CREATE TABLE Roster(Name TEXT, Species TEXT, IQ INT)") 11 | 12 | # Add some data into the database 13 | roster_data = ( 14 | ("Jean-Baptiste Zorg", "Human", 122), 15 | ("Korben Dallas", "Meat Popsicle", 100), 16 | ("Ak'not", "Mangalore", -5) 17 | ) 18 | c.executemany("INSERT INTO Roster VALUES(?, ?, ?)", roster_data) 19 | 20 | # Update the Species of Korben Dallas to "Human" 21 | c.execute("UPDATE Roster SET Species=? WHERE Name=?", 22 | ('Human', 'Korben Dallas')) 23 | 24 | # Display the names and IQs of everyone classified as Human 25 | c.execute("SELECT Name, IQ FROM Roster WHERE Species = 'Human'") 26 | for row in c.fetchall(): 27 | print row 28 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 14/Assignment solutions/14-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 14.1 review exercises 2 | 3 | import urllib2 4 | 5 | # Get the full HTML from the "dionysus" page 6 | my_address = "https://realpython.com/practice/dionysus.html" 7 | html_page = urllib2.urlopen(my_address) 8 | html_text = html_page.read() 9 | 10 | # Get the "Name" and "Favorite Color" using find() 11 | for tag in ["Name: ", "Favorite Color: "]: 12 | tag_start = html_text.find(tag) + len(tag) 13 | tag_end = html_text[tag_start:].find("<") 14 | # Remove extra spaces and newline padding 15 | print html_text[tag_start:tag_start+tag_end].strip(" \n") 16 | 17 | 18 | # Get the "Name" and "Favorite Color" using regular expressions 19 | import re 20 | # Match anything up until a new line or HTML tag; non-greedy 21 | for tag in ["Name: .*?[\n<]", "Favorite Color: .*?[\n<]"]: 22 | match_results = re.search(tag, html_text) 23 | # Remove the "Name: " or "Favorite Color: " label from first result 24 | result = re.sub(".*: ", "", match_results.group()) 25 | # Remove extra spaces and newline padding along with opening HTML tag 26 | print result.strip(" \n<") 27 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 14/Assignment solutions/14-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 14.2 review exercises 2 | 3 | import urllib2 4 | from bs4 import BeautifulSoup 5 | 6 | # Get the full HTML from the "profiles" page 7 | base_URL = "https://realpython.com/practice/" 8 | address = base_URL + "profiles.html" 9 | html_page = urllib2.urlopen(address) 10 | html_text = html_page.read() 11 | soup = BeautifulSoup(html_text) 12 | 13 | # Parse out all the values of the page links 14 | for anchor in soup.find_all("a"): 15 | # Could also have used urlparse.urljoin() to get absolute URL 16 | link_address = base_URL + anchor["href"] 17 | # Display the text in the HTML page of each link 18 | link_page = urllib2.urlopen(link_address) 19 | link_text = link_page.read() 20 | link_soup = BeautifulSoup(link_text) 21 | print link_soup.get_text() 22 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 14/Assignment solutions/14-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 14.3 review exercises 2 | 3 | import mechanize 4 | # from bs4 import BeautifulSoup 5 | 6 | # Start a mechanize browser and open the login page 7 | my_browser = mechanize.Browser() 8 | my_browser.open("https://realpython.com/practice/login.php") 9 | 10 | # Select the login form and input a username & password 11 | my_browser.select_form("login") 12 | my_browser["user"] = "zeus" 13 | my_browser["pwd"] = "ThunderDude" 14 | my_response = my_browser.submit() # submit form 15 | 16 | # Make sure we were redirected to the profiles page 17 | print my_response.geturl() 18 | 19 | # Return to the previous login page 20 | my_browser.back() 21 | 22 | # Try to log in with incorrect information 23 | my_browser.select_form("login") 24 | my_browser["user"] = "Hera" 25 | my_browser["pwd"] = "LightningLady" 26 | my_response = my_browser.submit() # submit form 27 | 28 | # See if we were redirected to the "error" page by searching for known text 29 | if my_response.get_data().find("Wrong username or password!") != -1: 30 | print "Login failed." 31 | else: 32 | print "Login success." 33 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 14/Assignment solutions/14-4 review exercises.py: -------------------------------------------------------------------------------- 1 | # 14.4 review exercises 2 | 3 | from time import sleep 4 | import mechanize 5 | from bs4 import BeautifulSoup 6 | 7 | # Create a Browser object 8 | my_browser = mechanize.Browser() 9 | 10 | # Obtain 1 stock quote per minute for the next 3 minutes 11 | for i in range(0, 3): 12 | html_page = my_browser.open("http://finance.yahoo.com/q?s=yhoo") 13 | html_text = html_page.get_data() 14 | 15 | my_soup = BeautifulSoup(html_text) 16 | 17 | # Grab the BeauitfulSoup stock quote string 18 | my_price_tags = my_soup.find_all("span", id="yfs_l84_yhoo") 19 | my_price = my_price_tags[0].string 20 | 21 | # Grab the timestamp 22 | my_time_tags = my_soup.find_all("span", id="yfs_market_time") 23 | my_time = my_time_tags[0].string 24 | my_time = my_time[:my_time.find(" - ")] # trim string to just the time 25 | 26 | print "The price of YHOO is: {} on {}".format(my_price, my_time) 27 | 28 | if i < 2: # Wait a minute if this isn't the last request 29 | sleep(60) 30 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 15/Assignment solutions/15-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 15.1 review exercises 2 | 3 | # Setup 4 | import numpy 5 | 6 | 7 | # Create a 3x3 array of the number 3 through 11 using reshape() 8 | first_matrix = numpy.arange(3, 12) 9 | first_matrix = first_matrix.reshape(3, 3) 10 | 11 | # Display the min, max and mean of all entries in the matrix 12 | print "Min is", first_matrix.min() 13 | print "Max is", first_matrix.max() 14 | print "Mean is", first_matrix.mean() 15 | 16 | # Square every entry and save in a new matrix 17 | second_matrix = first_matrix ** 2 18 | 19 | # Put first_matrix on top of second_matrix 20 | third_matrix = numpy.vstack([first_matrix, second_matrix]) 21 | 22 | # Calculate the dot product of third_matrix by first_matrix 23 | print numpy.dot(third_matrix, first_matrix) 24 | 25 | # Reshape third_matrix into a 3x3x2 matrix 26 | third_matrix = third_matrix.reshape(3, 3, 2) 27 | print third_matrix 28 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 15/Assignment solutions/pirates.py: -------------------------------------------------------------------------------- 1 | # 11.2 pirates.py 2 | # Graph pirates versus global warming 3 | 4 | from matplotlib import pyplot as plt 5 | import csv 6 | import os 7 | path = "C:/Real Python/Course materials/Chapter 15/Practice files" 8 | 9 | years = [] 10 | temperatures = [] 11 | pirates = [] 12 | 13 | with open(os.path.join(path, "pirates.csv"), "rb") as my_file: 14 | my_file_reader = csv.reader(my_file) 15 | my_file_reader.next() # skip header row 16 | for year, temperature, pirate_count in my_file_reader: 17 | years.append(year) 18 | temperatures.append(temperature) 19 | pirates.append(pirate_count) 20 | 21 | plt.plot(pirates, temperatures, "r-o") 22 | 23 | # label graph 24 | plt.title("Global temperature as a function of pirate population") 25 | plt.xlabel("Total pirates") 26 | plt.ylabel("Average global temperature (Celsius)") 27 | plt.axis([-300, 48000, 14, 16]) 28 | 29 | # annotate points with years 30 | for i in range(0, len(years)): 31 | plt.annotate(str(years[i]), xy=(pirates[i], temperatures[i])) 32 | 33 | # save and display graph 34 | plt.savefig(os.path.join(path, "Output/pirates.png")) 35 | plt.show() 36 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 15/Practice files/pirates.csv: -------------------------------------------------------------------------------- 1 | Year,Temperature,Pirates 2 | 1820,14.25,45000 3 | 1860,14.4,35000 4 | 1880,14.55,20000 5 | 1920,14.9,15000 6 | 1940,15.25,5000 7 | 1980,15.6,400 8 | 2000,15.9,17 9 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 16/Assignment solutions/16-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 16.2 review exercises 2 | 3 | # Create a button that takes on the value in an entry box 4 | 5 | 6 | from Tkinter import * 7 | 8 | 9 | def button_clicked(): 10 | ''' sets the button text to the text in the entry box ''' 11 | button.config(text=entry.get()) 12 | 13 | 14 | window = Tk() 15 | # Create and add button 16 | button = Button(text=" ", command=button_clicked) 17 | button.grid(row=1, column=1) 18 | # Create and add space for user entry of text 19 | entry = Entry(width=10) 20 | entry.grid(row=1, column=2) 21 | 22 | mainloop() 23 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 17/Assignment solutions/login.py: -------------------------------------------------------------------------------- 1 | # 17-1 review exercise 2 | 3 | # This script needs to be placed in a project folder with 4 | # the appropriate YAML configuration file 5 | 6 | import webapp2 7 | 8 | 9 | class MainPage(webapp2.RequestHandler): 10 | def get(self): 11 | username = self.request.get("myName") 12 | if username == "": 13 | welcomeString = "" 14 | else: 15 | welcomeString = "Hi there, {}!".format(username) 16 | 17 | self.response.headers["Content-Type"] = "text/html" 18 | self.response.write(""" 19 | 20 | Enter your name... 21 | 22 | {}
23 |
24 |
25 | 26 |
27 | 28 | """.format(welcomeString)) 29 | 30 | routes = [('/', MainPage)] 31 | my_app = webapp2.WSGIApplication(routes, debug=True) 32 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 17/first_app/app.yaml: -------------------------------------------------------------------------------- 1 | application: temperature-converter 2 | version: 1 3 | runtime: python27 4 | api_version: 1 5 | threadsafe: false 6 | 7 | handlers: 8 | - url: /.* 9 | script: temperature.my_app 10 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 17/first_app/hello.py: -------------------------------------------------------------------------------- 1 | import webapp2 2 | import cgi 3 | 4 | 5 | class MainPage(webapp2.RequestHandler): 6 | def get(self): 7 | self.response.headers["Content-Type"] = "text/html" 8 | self.response.write(""" 9 | 10 | Enter your name... 11 | 12 |
13 |
14 | 15 |
16 | 17 | """) 18 | 19 | 20 | class Greeting(webapp2.RequestHandler): 21 | def post(self): 22 | username = cgi.escape(self.request.get("myName")) 23 | welcome_string = """ 24 | Hi there, {}! 25 | """.format(username) 26 | self.response.headers["Content-Type"] = "text/html" 27 | self.response.write(welcome_string) 28 | 29 | routes = [('/', MainPage), ('/welcome', Greeting)] 30 | my_app = webapp2.WSGIApplication(routes, debug=True) 31 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 17/first_app/temperature.py: -------------------------------------------------------------------------------- 1 | import webapp2 2 | 3 | 4 | def convert_temp(cel_temp): 5 | ''' convert Celsius temperature to Fahrenheit temperature ''' 6 | if cel_temp == "": 7 | return "" 8 | try: 9 | far_temp = float(cel_temp) * 9/5 + 32 10 | far_temp = round(far_temp, 3) # round to three decimal places 11 | return str(far_temp) 12 | except ValueError: # user entered non-numeric temperature 13 | return "invalid input" 14 | 15 | 16 | class MainPage(webapp2.RequestHandler): 17 | def get(self): 18 | cel_temp = self.request.get("cel_temp") 19 | far_temp = convert_temp(cel_temp) 20 | 21 | self.response.headers["Content-Type"] = "text/html" 22 | self.response.write(""" 23 | 24 | Temperature Converter 25 | 26 |
27 | Celsius temperature: 29 |
30 | Fahrenheit temperature: {} 31 |
32 | 33 | """.format(cel_temp, far_temp)) 34 | 35 | routes = [('/', MainPage)] 36 | my_app = webapp2.WSGIApplication(routes, debug=True) 37 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 17/poetry/app.yaml: -------------------------------------------------------------------------------- 1 | application: poem-generator 2 | version: 1 3 | runtime: python27 4 | api_version: 1 5 | threadsafe: false 6 | 7 | handlers: 8 | - url: /.* 9 | script: makePoems.my_app 10 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 2/Assignment solutions/2-4 review exercises.py: -------------------------------------------------------------------------------- 1 | # 2.4 review exercises 2 | 3 | 4 | ''' The following line won't run because of a syntax error ''' 5 | print "hi 6 | 7 | # We didn't close the double quotes at the end of the string. 8 | # The line above" needed to have been: 9 | # print "hi" 10 | 11 | 12 | ''' The following lines won't run properly, 13 | even if the syntax error in the line above is corrected, 14 | because of a run-time error ''' 15 | print hello 16 | 17 | # We meant to print the string "hello"; 18 | # a variable named 'hello' doesn't exist yet. 19 | # This line could have been: 20 | # myString = "hello" 21 | # print myString 22 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 2/Assignment solutions/2-5 review exercises.py: -------------------------------------------------------------------------------- 1 | # 2.5 review exercises 2 | 3 | # The following lines can also be typed 4 | # directly into the interactive window as well: 5 | 6 | 7 | # display a string directly 8 | print "hello" 9 | 10 | 11 | # display the contents of a string variable 12 | my_string = "hi" 13 | print my_string 14 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 4/Assignment solutions/4-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 4.1 review exercises 2 | 3 | print 'There are "double quotes" in this string.' 4 | 5 | print "This string's got an apostrophe." 6 | 7 | print '''This string was written on multiple lines, 8 | and it displays across multiple lines''' 9 | 10 | print "This one-line string was written out \ 11 | using multiple lines" 12 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 4/Assignment solutions/4-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 4.2 review exercises 2 | 3 | 4 | # Display the number of letters in the string 5 | my_word = "antidisestablishmentarianism" 6 | print len(my_word) 7 | 8 | # Concatenate two strings together 9 | string_left = "bat" 10 | string_right = "man" 11 | print string_left + string_right 12 | 13 | # Display two strings together, with a space in between 14 | string_one = "heebie" 15 | string_two = "jeebies" 16 | print string_one, string_two 17 | 18 | 19 | # Use subscripting to display part of a string 20 | print "bazinga"[2:6] 21 | 22 | 23 | # A more advanced way to do the above example would be: 24 | my_string = "bazinga" 25 | start_index = 2 26 | print my_string[start_index:len(my_string)-start_index+1] 27 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 4/Assignment solutions/4-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 4.3 review exercises 2 | 3 | # Take input from the user and display that input back 4 | my_input = raw_input("Type something: ") 5 | print my_input 6 | 7 | # Display the input string converted to lower-case letters 8 | print my_input.lower() 9 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 4/Assignment solutions/first_letter.py: -------------------------------------------------------------------------------- 1 | # 4.3 first_letter.py 2 | # Return the upper-case first letter entered by the user 3 | 4 | user_input = raw_input("Tell me your password: ") 5 | first_letter = user_input[0] 6 | print "The first letter you entered was:", first_letter.upper() 7 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 5/Assignment solutions/5-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 5.1 review exercises 2 | 3 | 4 | # Store an integer as a string 5 | my_integer_string = "6" 6 | 7 | # Convert the 'integer' string into an int object using int() 8 | # Multiply the integer by 7 and display the result 9 | print int(my_integer_string) * 7 10 | 11 | 12 | # Store a floating-point number as a string 13 | my_float_string = "6.01" 14 | 15 | # Convert the 'float' string into a number using float() 16 | # Multiply the number by 7 and display the result 17 | print float(my_float_string) * 7 18 | 19 | 20 | # Create a string and an int object, then display them together 21 | my_string = "mp" 22 | my_int = 3 23 | print my_string + str(my_int) 24 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 5/Assignment solutions/5-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 5.2 review exercises 2 | 3 | weight = 0.2 4 | animal = "newt" 5 | 6 | # Concatenate a number and a string in one print statement 7 | print str(weight) + " kg is the weight of the newt." 8 | 9 | # Use format() to print a number and a string inside of another string 10 | print "{} kg is the weight of the {}.".format(weight, animal) 11 | 12 | # Use format() to add objects inside a string using index numbers 13 | # (Here we reversed the arguments - just because we could.) 14 | print "{1} kg is the weight of the {0}.".format(animal, weight) 15 | 16 | # Use format() to print new objects inside a string 17 | print "{} kg is the weight of the {}.".format(0.2, "newt") 18 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 5/Assignment solutions/5-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 5.3 review exercises 2 | 3 | 4 | # Cannot find the string "a" in the string "AAA": 5 | print "AAA".find("a") 6 | 7 | 8 | # Try to find a number inside a string; 9 | # use str() to convert the number first 10 | version = "version 2.0" 11 | v_num = 2.0 12 | print version.find(str(v_num)) 13 | 14 | 15 | # Try to find an upper-case "X" in user input: 16 | my_input = raw_input("Type something: ") 17 | print my_input.find("X") 18 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 5/Assignment solutions/translate.py: -------------------------------------------------------------------------------- 1 | # 5.3 translate.py 2 | # Turn a user's input into leetspeak 3 | 4 | my_text = raw_input("Enter some text: ") 5 | 6 | my_text = my_text.replace("a", "4") 7 | my_text = my_text.replace("b", "8") 8 | my_text = my_text.replace("e", "3") 9 | my_text = my_text.replace("l", "1") 10 | my_text = my_text.replace("o", "0") 11 | my_text = my_text.replace("s", "5") 12 | my_text = my_text.replace("t", "7") 13 | 14 | print my_text 15 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 6/Assignment solutions/6-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 6.1 review exercises 2 | 3 | 4 | #from __future__ import division 5 | 6 | print 5 / 2 7 | # This line will perform "integer division" until 8 | # the comment is removed from the "import" line above 9 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 6/Assignment solutions/6-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 6.2 review exercises 2 | 3 | 4 | def cube(num): 5 | ''' Returns the cube of the input number ''' 6 | cube_num = num * num * num 7 | return cube_num 8 | 9 | print "0 cubed is", cube(0) 10 | print "2 cubed is", cube(2) 11 | 12 | 13 | def multiply(num1, num2): 14 | ''' Returns the result of multiplying two input numbers ''' 15 | return num1 * num2 16 | 17 | mult_result = multiply(2, 5) 18 | print "2 times 5 is", mult_result 19 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 6/Assignment solutions/6-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 6.3 review exercises 2 | 3 | 4 | # print the integer 2 through 10 using a "for" loop 5 | for i in range(2, 11): 6 | print i 7 | 8 | 9 | # print the integer 2 through 10 using a "while" loop 10 | i = 2 11 | while (i < 11): 12 | print i 13 | i = i + 1 14 | 15 | 16 | def doubles(num): 17 | ''' Return the result of multiplying an input number by 2 ''' 18 | return num * 2 19 | 20 | # Call doubles to double the number 2 three times 21 | my_num = 2 22 | for i in range(0, 3): 23 | my_num = doubles(my_num) 24 | print my_num 25 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 6/Assignment solutions/exponent.py: -------------------------------------------------------------------------------- 1 | # 6.1 exponent.py 2 | # Receive two input numbers and calculate their power 3 | 4 | base = raw_input("Enter a base: ") 5 | exponent = raw_input("Enter an exponent: ") 6 | result = float(base) ** float(exponent) 7 | print "{} to the power of {} = {}".format(base, exponent, result) 8 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 6/Assignment solutions/invest.py: -------------------------------------------------------------------------------- 1 | # 6.3 invest.py 2 | # calculate compound interest to track the growth of an investment 3 | 4 | 5 | def invest(amount, rate, time): 6 | print "principal amount: ${}".format(amount) 7 | print "annual rate of return:", rate 8 | for t in range(1, time + 1): 9 | amount = amount * (1 + rate) 10 | print "year {}: ${}".format(t, amount) 11 | print 12 | 13 | invest(100, .05, 8) 14 | invest(2000, .025, 5) 15 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 6/Assignment solutions/temperature.py: -------------------------------------------------------------------------------- 1 | # 6.2 temperature.py 2 | # Convert Celsius and Fahrenheit temperatures using functions 3 | 4 | from __future__ import division 5 | 6 | 7 | def convert_cel_to_far(cel_temp): 8 | far_temp = cel_temp * 9/5 + 32 9 | return far_temp 10 | 11 | 12 | def convert_far_to_cel(far_temp): 13 | cel_temp = (far_temp - 32) * 5/9 14 | return cel_temp 15 | 16 | temp1 = 72 17 | print "{} degrees F = {} degrees C".format(temp1, convert_far_to_cel(temp1)) 18 | 19 | temp2 = 37 20 | print "{} degrees C = {} degrees F".format(temp2, convert_cel_to_far(temp2)) 21 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/8-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.1 review exercises 2 | 3 | 4 | # Test whether these expressions are True or False 5 | print 1 <= 1 6 | print 1 != 1 7 | print 1 != 2 8 | print "good" != "bad" 9 | print "good" != "Good" 10 | print 123 == "123" 11 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/8-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.2 review exercises 2 | 3 | 4 | # Test whether these expressions are True or False 5 | print (1 <= 1) and (1 != 1) 6 | print not (1 != 2) 7 | print ("good" != "bad") or False 8 | print ("good" != "Good") and not (1 == 1) 9 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/8-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.3 review exercises 2 | 3 | 4 | # Display whether the length of user input is <, > or = 5 characters 5 | my_input = raw_input("Type something: ") 6 | 7 | if len(my_input) < 5: 8 | print "Your input is less than 5 characters long." 9 | elif len(my_input) > 5: 10 | print "Your input is greater than 5 characters long." 11 | else: 12 | print "Your input is 5 characters long." 13 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/8-4 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.4 review exercises 2 | 3 | 4 | # Run in an infinite loop until the user types "q" or "Q" 5 | while True: 6 | my_input = raw_input('Type "q" or "Q" to quit: ') 7 | if my_input.upper() == "Q": 8 | break 9 | 10 | # Display every number from 1 through 50 except multiples of 3 11 | for i in range(1, 51): 12 | if i % 3 == 0: 13 | continue 14 | print i 15 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/8-5 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.5 review exercises 2 | 3 | 4 | # Ask the user to enter an integer. 5 | # Repeat the process if the user hasn't entered an integer. 6 | repeat = True 7 | while repeat: 8 | try: 9 | my_input = raw_input("Type an integer: ") 10 | print int(my_input) 11 | repeat = False 12 | except ValueError: 13 | print "try again" 14 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/8-6 review exercises.py: -------------------------------------------------------------------------------- 1 | # 8.6 review exercises 2 | 3 | from __future__ import division 4 | from random import randint 5 | 6 | 7 | # Simulate the toss of a die 8 | print randint(1, 6) 9 | 10 | 11 | # Simulate 10,000 throws of dice and display the average result 12 | trials = 10000 13 | total = 0 14 | for trial in range(0, trials): 15 | total += randint(1, 6) 16 | 17 | avg_result = total / trials 18 | print "The average result of {} throws was {}".format(trials, avg_result) 19 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/coin_toss.py: -------------------------------------------------------------------------------- 1 | # 8.6.2 coin_toss.py 2 | # Simulate the results of a series of coin tosses and track the results 3 | 4 | from __future__ import division 5 | from random import randint 6 | 7 | flips = 0 8 | trials = 10000 9 | 10 | for trial in range(0, trials): 11 | flips += 1 # first flip 12 | if randint(0, 1) == 0: # flipped tails on first flip 13 | while randint(0, 1) == 0: # keep flipping tails 14 | flips += 1 15 | flips += 1 # finally flipped heads 16 | else: # otherwise, flipped heads on first flip 17 | while randint(0, 1) == 1: # keep flipping heads 18 | flips += 1 19 | flips += 1 # finally flipped tails 20 | 21 | print flips / trials 22 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/coin_toss_alternative.py: -------------------------------------------------------------------------------- 1 | # 8.6.2 coin_toss_alternative.py 2 | # Simulate the results of a series of coin tosses and track the results 3 | 4 | from __future__ import division 5 | from random import randint 6 | 7 | 8 | trials = 100000 9 | flips = 0 10 | 11 | for trial in range(1, trials): 12 | first_flip = randint(0, 1) 13 | flips += 1 14 | while randint(0, 1) == first_flip: 15 | flips += 1 16 | flips += 1 17 | 18 | print "The average number of coin flips was {0}".format(flips/trials) 19 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/election.py: -------------------------------------------------------------------------------- 1 | # 8.6.1 election.py 2 | # Simulate the results of an election using a Monte Carlo simulation 3 | 4 | from __future__ import division 5 | from random import random 6 | 7 | total_A_wins = 0 8 | total_B_wins = 0 9 | 10 | trials = 100000 11 | for trial in range(0, trials): 12 | A_win = 0 13 | B_win = 0 14 | if random() < .87: # 1st region 15 | A_win += 1 16 | else: 17 | B_win += 1 18 | if random() < .65: # 2nd region 19 | A_win += 1 20 | else: 21 | B_win += 1 22 | if random() < .17: # 3rd region 23 | A_win += 1 24 | else: 25 | B_win += 1 26 | # determine overall election outcome 27 | if A_win > B_win: 28 | total_A_wins += 1 29 | else: 30 | total_B_wins += 1 31 | 32 | print "Probability A wins:", total_A_wins/trials 33 | print "Probability B wins:", total_B_wins/trials 34 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 8/Assignment solutions/factors.py: -------------------------------------------------------------------------------- 1 | # 8.3 factors.py 2 | # display all the factors of a number chosen by the user 3 | 4 | num = int(raw_input("Enter a positive integer: ")) 5 | for divisor in range(1, num+1): 6 | if num % divisor == 0: 7 | print "{} is a divisor of {}".format(divisor, num) 8 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 9/Assignment solutions/9-1 review exercises.py: -------------------------------------------------------------------------------- 1 | # 9.1 review exercises 2 | 3 | 4 | desserts = ["ice cream", "cookies"] 5 | 6 | # Sort the desserts list alphabetically 7 | desserts.sort() 8 | 9 | # Display the sorted list 10 | print desserts 11 | 12 | # Display the index value of "ice cream" 13 | print desserts.index("ice cream") 14 | 15 | # Copy the contents of the "desserts" list into a new "food" list 16 | food = desserts[:] 17 | 18 | # Add some food to the list 19 | food.append("broccoli") 20 | food.append("turnips") 21 | 22 | # Display the contents of both lists 23 | print desserts 24 | print food 25 | 26 | # Take "cookies" out of the "food" list 27 | food.remove("cookies") 28 | 29 | # Display the first two items in the "food" list 30 | print food[0:2] 31 | 32 | # Create a "breakfast" list full of cookies and display it 33 | my_breakfast = "cookies, cookies, cookies" 34 | breakfast = my_breakfast.split(", ") 35 | print breakfast 36 | 37 | """ 38 | Define a function that takes a list of numbers, `[2, 4, 8, 16, 32, 64]`, as the 39 | argument and then outputs only the numbers from the list that fall between 1 40 | and 20 (inclusive) 41 | """ 42 | 43 | 44 | def print_list(list_of_nums): 45 | for num in list_of_nums: 46 | if num >= 2 and num <= 20: 47 | print num 48 | 49 | list_of_numbers = [2, 4, 8, 16, 32, 64] 50 | print_list(list_of_numbers) 51 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 9/Assignment solutions/9-2 review exercises.py: -------------------------------------------------------------------------------- 1 | # 9.2 review exercises 2 | 3 | 4 | # Create a tuple "cardinal_nums" with "first", "second" and "third" 5 | cardinal_nums = ("first", "second", "third") 6 | 7 | # Display the second object in the tuple 8 | print cardinal_nums[1] 9 | 10 | 11 | # unpack the tuple into three string and display them 12 | pos1, pos2, pos3 = cardinal_nums 13 | print pos1 14 | print pos2 15 | print pos3 16 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 9/Assignment solutions/9-3 review exercises.py: -------------------------------------------------------------------------------- 1 | # 9.3 review exercises 2 | 3 | 4 | # Create an empty dictionary 5 | birthdays = {} 6 | 7 | # Add some key-value pairs to the dictionary 8 | birthdays["Luke Skywalker"] = "5/25/19" 9 | birthdays["Obi-Wan Kenobi"] = "3/11/57" 10 | birthdays["Darth Vader"] = "4/1/41" 11 | 12 | # Check if "Yoda" and "Darth Vader exist; if not, add them 13 | if not "Yoda" in birthdays: 14 | birthdays["Yoda"] = "unknown" 15 | if not "Darth Vader" in birthdays: 16 | birthdays["Darth Vader"] = "unknown" 17 | 18 | ## Bonus points: you could instead loop over a list of names to check 19 | #for name in ["Yoda", "Darth Vader"]: 20 | # if not name in birthdays: 21 | # birthdays[name] = "unknown" 22 | 23 | # Display the contents of the dictionary, one pair at a time 24 | for name in birthdays: 25 | print name, birthdays[name] 26 | 27 | # Remove "Darth Vader" 28 | del(birthdays["Darth Vader"]) 29 | print birthdays 30 | 31 | 32 | # Bonus: could have created dictionary by passing a list to dict() 33 | birthdays = dict([("Luke Skywalker", "5/25/19"), 34 | ("Obi-Wan Kenobi", "3/11/57"), 35 | ("Darth Vader", "4/1/41")]) 36 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 9/Assignment solutions/capital_city_loop.py: -------------------------------------------------------------------------------- 1 | from capitals import capitals_dict 2 | import random 3 | 4 | 5 | def capital_game(state, capital): 6 | while True: 7 | guess = raw_input("What is the capital of '{}'? ".format(state)).lower() 8 | if guess == "exit": 9 | print "The capital of '{}' is '{}'.".format(state, capital) 10 | print "Goodbye" 11 | break 12 | elif guess == (capital).lower(): 13 | print "Correct! Nice job." 14 | break 15 | 16 | 17 | state = random.choice(capitals_dict.keys()) 18 | capital = capitals_dict[state] 19 | capital_game(state, capital) 20 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 9/Assignment solutions/capitals.py: -------------------------------------------------------------------------------- 1 | capitals_dict = { 2 | 'Alabama': 'Montgomery', 3 | 'Alaska': 'Juneau', 4 | 'Arizona': 'Phoenix', 5 | 'Arkansas': 'Little Rock', 6 | 'California': 'Sacramento', 7 | 'Colorado': 'Denver', 8 | 'Connecticut': 'Hartford', 9 | 'Delaware': 'Dover', 10 | 'Florida': 'Tallahassee', 11 | 'Georgia': 'Atlanta', 12 | 'Hawaii': 'Honolulu', 13 | 'Idaho': 'Boise', 14 | 'Illinois': 'Springfield', 15 | 'Indiana': 'Indianapolis', 16 | 'Iowa': 'Des Moines', 17 | 'Kansas': 'Topeka', 18 | 'Kentucky': 'Frankfort', 19 | 'Louisiana': 'Baton Rouge', 20 | 'Maine': 'Augusta', 21 | 'Maryland': 'Annapolis', 22 | 'Massachusetts': 'Boston', 23 | 'Michigan': 'Lansing', 24 | 'Minnesota': 'Saint Paul', 25 | 'Mississippi': 'Jackson', 26 | 'Missouri': 'Jefferson City', 27 | 'Montana': 'Helena', 28 | 'Nebraska': 'Lincoln', 29 | 'Nevada': 'Carson City', 30 | 'New Hampshire': 'Concord', 31 | 'New Jersey': 'Trenton', 32 | 'New Mexico': 'Santa Fe', 33 | 'New York': 'Albany', 34 | 'North Carolina': 'Raleigh', 35 | 'North Dakota': 'Bismarck', 36 | 'Ohio': 'Columbus', 37 | 'Oklahoma': 'Oklahoma City', 38 | 'Oregon': 'Salem', 39 | 'Pennsylvania': 'Harrisburg', 40 | 'Rhode Island': 'Providence', 41 | 'South Carolina': 'Columbia', 42 | 'South Dakota': 'Pierre', 43 | 'Tennessee': 'Nashville', 44 | 'Texas': 'Austin', 45 | 'Utah': 'Salt Lake City', 46 | 'Vermont': 'Montpelier', 47 | 'Virginia': 'Richmond', 48 | 'Washington': 'Olympia', 49 | 'West Virginia': 'Charleston', 50 | 'Wisconsin': 'Madison', 51 | 'Wyoming': 'Cheyenne', 52 | } 53 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 9/Assignment solutions/cats_with_hats.py: -------------------------------------------------------------------------------- 1 | def get_cats_with_hats(array_of_cats): 2 | cats_with_hats_on = [] 3 | for num in xrange(1, 100+1): 4 | for cat in xrange(1, 100+1): 5 | if cat % num == 0: 6 | if array_of_cats[cat] is True: 7 | array_of_cats[cat] = False 8 | else: 9 | array_of_cats[cat] = True 10 | for cat in xrange(1, 100+1): 11 | if cats[cat] is True: 12 | cats_with_hats_on.append(cat) 13 | return cats_with_hats_on 14 | 15 | cats = [False] * (100+1) 16 | print get_cats_with_hats(cats) 17 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 9/Assignment solutions/cats_with_hats_alternative.py: -------------------------------------------------------------------------------- 1 | number_of_cats = 100 2 | cats_with_hats = [] 3 | number_of_laps = 100 4 | 5 | # We want the laps to be from 1 to 100 instead of 0 to 99 6 | for lap in range(1, number_of_laps + 1): 7 | for cat in xrange(1, number_of_cats + 1): 8 | 9 | # Only look at cats that are divisible by the lap 10 | if cat % lap == 0: 11 | if cat in cats_with_hats: 12 | cats_with_hats.remove(cat) 13 | else: 14 | cats_with_hats.append(cat) 15 | 16 | print cats_with_hats 17 | -------------------------------------------------------------------------------- /_old/Course materials/Chapter 9/Assignment solutions/cats_with_hats_dict.py: -------------------------------------------------------------------------------- 1 | theCats = {} 2 | 3 | for i in xrange(1, 101): 4 | theCats[i] = False 5 | 6 | for i in xrange(1, 101): 7 | for cats, hats in theCats.iteritems(): 8 | if cats % i == 0: 9 | if theCats[cats]: 10 | theCats[cats] = False 11 | else: 12 | theCats[cats] = True 13 | 14 | for cats, hats in theCats.iteritems(): 15 | if theCats[cats]: 16 | print "Cat {} has a hat.".format(cats) 17 | else: 18 | print "Cat {} is hatless!".format(cats) 19 | -------------------------------------------------------------------------------- /_old/Course materials/oop/dog_class.py: -------------------------------------------------------------------------------- 1 | class Dog(object): 2 | 3 | # Class Attribute 4 | species = 'mammal' 5 | 6 | # Initializer / Instance Attributes 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | 12 | # Instantiate the Dog object 13 | philo = Dog("Philo", 5) 14 | mikey = Dog("Mikey", 6) 15 | 16 | # Access the instance attributes 17 | print "{} is {} and {} is {}.".format( 18 | philo.name, philo.age, mikey.name, mikey.age) 19 | 20 | # Is Philo a mammal? 21 | if philo.species == "mammal": 22 | print "{0} is a {1}!".format(philo.name, philo.species) 23 | -------------------------------------------------------------------------------- /_old/Course materials/oop/dog_inheritence.py: -------------------------------------------------------------------------------- 1 | # Parent class 2 | class Dog(object): 3 | 4 | # Class attribute 5 | species = 'mammal' 6 | 7 | # Initializer / Instance attributes 8 | def __init__(self, name, age): 9 | self.name = name 10 | self.age = age 11 | 12 | # instance method 13 | def description(self): 14 | return self.name, self.age 15 | 16 | # instance method 17 | def speak(self, sound): 18 | return "%s says %s" % (self.name, sound) 19 | 20 | 21 | # child class (inherits from Dog() class) 22 | class RussellTerrier(Dog): 23 | def run(self, speed): 24 | return "%s runs %s" % (self.name, speed) 25 | 26 | 27 | # child class (inherits from Dog() class) 28 | class Bulldog(Dog): 29 | def run(self, speed): 30 | return "%s runs %s" % (self.name, speed) 31 | 32 | 33 | # child classes inherit attributes and 34 | # behaviors from the parent class 35 | jim = Bulldog("Jim", 12) 36 | print jim.description() 37 | 38 | # child classes have specific attributes 39 | # and behaviors as well 40 | print jim.run("slow") 41 | -------------------------------------------------------------------------------- /_old/Course materials/oop/dog_instance_methods.py: -------------------------------------------------------------------------------- 1 | class Dog(object): 2 | 3 | # Class Attribute 4 | species = 'mammal' 5 | 6 | # Initializer / Instance Attributes 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | # instance method 12 | def description(self): 13 | return self.name, self.age 14 | 15 | # instance method 16 | def speak(self, sound): 17 | return "%s says %s" % (self.name, sound) 18 | 19 | # Instantiate the Dog object 20 | mikey = Dog("Mikey", 6) 21 | 22 | # call our instance methods 23 | print mikey.description() 24 | print mikey.speak("Gruff Gruff") 25 | -------------------------------------------------------------------------------- /_old/Course materials/oop/dog_isinstance.py: -------------------------------------------------------------------------------- 1 | # Parent class 2 | class Dog(object): 3 | 4 | # Class attribute 5 | species = 'mammal' 6 | 7 | # Initializer / Instance attributes 8 | def __init__(self, name, age): 9 | self.name = name 10 | self.age = age 11 | 12 | # instance method 13 | def description(self): 14 | return self.name, self.age 15 | 16 | # instance method 17 | def speak(self, sound): 18 | return "%s says %s" % (self.name, sound) 19 | 20 | 21 | # child class (inherits from Dog() class) 22 | class RussellTerrier(Dog): 23 | def run(self, speed): 24 | return "%s runs %s" % (self.name, speed) 25 | 26 | 27 | # child class (inherits from Dog() class) 28 | class Bulldog(Dog): 29 | def run(self, speed): 30 | return "%s runs %s" % (self.name, speed) 31 | 32 | 33 | # child classes inherit attributes and 34 | # behaviors from the parent class 35 | jim = Bulldog("Jim", 12) 36 | print jim.description() 37 | 38 | # child classes have specific attributes 39 | # and behaviors as well 40 | print jim.run("slow") 41 | 42 | # is jim an instance of Dog()? 43 | print isinstance(jim, Dog) 44 | 45 | # is julie an instance of Dog()? 46 | julie = Dog("Julie", 100) 47 | print isinstance(julie, Dog) 48 | 49 | # is johnny walker an instance of Bulldog() 50 | johnnywalker = RussellTerrier("Johnny Walker", 4) 51 | print isinstance(johnnywalker, Bulldog) 52 | 53 | # is julie and instance of jim? 54 | print isinstance(julie, jim) 55 | -------------------------------------------------------------------------------- /_old/Course materials/oop/dog_walking.py: -------------------------------------------------------------------------------- 1 | # parent class 2 | class Pet(object): 3 | 4 | dogs = [] 5 | 6 | def __init__(self, dogs): 7 | self.dogs = dogs 8 | 9 | def walk(self): 10 | for dog in self.dogs: 11 | print dog.walk() 12 | 13 | 14 | # parent class 15 | class Dog(object): 16 | 17 | # class attribute 18 | species = 'mammal' 19 | is_hungry = True 20 | 21 | # initializer / instance attributes 22 | def __init__(self, name, age): 23 | self.name = name 24 | self.age = age 25 | 26 | # instance method 27 | def description(self): 28 | return self.name, self.age 29 | 30 | # instance method 31 | def speak(self, sound): 32 | return "%s says %s" % (self.name, sound) 33 | 34 | # instance method 35 | def eat(self): 36 | self.is_hungry = False 37 | 38 | def walk(self): 39 | return "%s is walking!" % (self.name) 40 | 41 | 42 | # child class (inherits from Dog() class) 43 | class RussellTerrier(Dog): 44 | def run(self, speed): 45 | return "%s runs %s" % (self.name, speed) 46 | 47 | 48 | # child class (inherits from Dog() class) 49 | class Bulldog(Dog): 50 | def run(self, speed): 51 | return "%s runs %s" % (self.name, speed) 52 | 53 | # create instances of dogs 54 | my_dogs = [Bulldog("Tom", 6), RussellTerrier("Fletcher", 7), Dog("Larry", 9)] 55 | 56 | # instantiate the Pet() class 57 | my_pets = Pet(my_dogs) 58 | 59 | # output 60 | my_pets.walk() 61 | -------------------------------------------------------------------------------- /_old/Course materials/oop/github_with_class.py: -------------------------------------------------------------------------------- 1 | from urllib2 import Request, urlopen 2 | 3 | 4 | class Github(object): 5 | 6 | def __init__(self, username): 7 | self.username = username 8 | self.base_url = 'https://api.github.com/users/' 9 | 10 | def get_user_info(self): 11 | full_url = "{0}{1}".format(self.base_url, self.username) 12 | request = Request(full_url) 13 | handler = urlopen(request) 14 | if handler.getcode() == 200: 15 | return handler.read() 16 | 17 | def get_user_repos(self): 18 | full_url = "{0}{1}/repos".format(self.base_url, self.username) 19 | request = Request(full_url) 20 | handler = urlopen(request) 21 | if handler.getcode() == 200: 22 | return handler.read() 23 | 24 | 25 | user = Github('mjhea0') 26 | print user.get_user_info() 27 | print user.get_user_repos() 28 | -------------------------------------------------------------------------------- /_old/Course materials/oop/oldest_dog.py: -------------------------------------------------------------------------------- 1 | class Dog(object): 2 | 3 | # Class Attribute 4 | species = 'mammal' 5 | 6 | # Initializer / Instance Attributes 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | 12 | # Instantiate the Dog object 13 | jake = Dog("Jake", 7) 14 | doug = Dog("Doug", 4) 15 | william = Dog("William", 5) 16 | 17 | 18 | # Determine the oldest dog 19 | def get_biggest_number(*args): 20 | return max(args) 21 | 22 | # output 23 | print "The oldest dog is {} years old.".format( 24 | get_biggest_number(jake.age, doug.age, william.age)) 25 | -------------------------------------------------------------------------------- /_old/Course materials/oop/pet_class.py: -------------------------------------------------------------------------------- 1 | # parent class 2 | class Pet(object): 3 | 4 | dogs = [] 5 | 6 | def __init__(self, dogs): 7 | self.dogs = dogs 8 | 9 | 10 | # parent class 11 | class Dog(object): 12 | 13 | # class attribute 14 | species = 'mammal' 15 | is_hungry = True 16 | 17 | # initializer / Instance attributes 18 | def __init__(self, name, age): 19 | self.name = name 20 | self.age = age 21 | 22 | # instance method 23 | def description(self): 24 | return self.name, self.age 25 | 26 | # instance method 27 | def speak(self, sound): 28 | return "%s says %s" % (self.name, sound) 29 | 30 | # instance method 31 | def eat(self): 32 | self.is_hungry = False 33 | 34 | 35 | # child class (inherits from Dog() class) 36 | class RussellTerrier(Dog): 37 | def run(self, speed): 38 | return "%s runs %s" % (self.name, speed) 39 | 40 | 41 | # child class (inherits from Dog() class) 42 | class Bulldog(Dog): 43 | def run(self, speed): 44 | return "%s runs %s" % (self.name, speed) 45 | 46 | # create instances of dogs 47 | my_dogs = [Bulldog("Tom", 6), RussellTerrier("Fletcher", 7), Dog("Larry", 9)] 48 | 49 | # instantiate the Pet() class 50 | my_pets = Pet(my_dogs) 51 | 52 | # output 53 | print "I have {} dogs.".format(len(my_pets.dogs)), 54 | for dog in my_pets.dogs: 55 | dog.eat() 56 | print "{} is {}.".format(dog.name, dog.age), 57 | print "And they're all {}s, of course.".format(dog.species), 58 | if dog.is_hungry is True: 59 | print "My dogs are hungry." 60 | else: 61 | print "My dogs are not hungry." 62 | -------------------------------------------------------------------------------- /_old/Course materials/regular_expressions/_clean_data.txt: -------------------------------------------------------------------------------- 1 | Melinda Stanley (520)526-8523 2013/06/27 Ap #397-1051 Ut, Rd. Fort Worth TX Purus Gravida Rose Wood (833)559-0524 2015/01/14 540-715 Massa. St. Minneapolis MN Quis Diam September Fulton (599)759-0669 2015/04/06 Ap #538-1934 Est Road Burlington VT Leo Consulting Ignatius Simon (134)600-3345 2015/05/10 8120 Netus Street Augusta GA Tempor Erat Neque Brady Cruz (283)940-6558 2014/02/03 126-8307 Nunc Rd. Athens GA Ac Risus Roary Mosley (668)498-6240 2014/12/08 P.O. Box 265, 6218 Viverra. St. Columbia MO Mauris Non Institute Liberty Levy (602)734-2959 2015/05/17 697-3414 Aliquet Av. Dallas TX Lectus Consulting Yuli Waters (364)703-2081 2014/03/15 518-3109 Magna, Ave Juneau AK Quisque Company Guy Norton (484)388-8334 2015/05/20 Ap #102-3787 Scelerisque Rd. Wilmington DE Dignissim Tempor Arcu Harrison Garza (392)293-2493 2013/11/29 Ap #437-9630 Vestibulum Av. Stamford CT Aliquet Wallace Graham (615)659-3227 2014/09/14 4267 Sodales St. Broken Arrow OK At Arcu Vestibulum Company Haviva Webb (202)227-4282 2015/03/04 P.O. Box 516, 7826 Semper St. Fort Collins CO Dui Ltd Jasmine Wall (789)957-4807 2013/09/22 Ap #991-8460 Aliquam Rd. Birmingham AL Maecenas Libero Barbara Rosales (510)410-6406 2014/03/31 P.O. Box 720, 7832 Orci. Road Mobile AL Fermentum Chancellor Oneal (875)552-8867 2015/03/12 394-1338 Nibh. Rd. Biloxi MS Dui Ltd Colette Pollard (989)348-5958 2014/06/07 Ap #157-9280 Proin Rd. Southaven MS Dapibus Rutrum Jasper Gordon (d{3})591-0740 2015/05/02 P.O. Box 381, 4896 Sed Avenue Akron OH Pharetra Ut Kane Munoz (542)329-7528 2014/04/06 Ap #387-5145 Eu Avenue Great Falls MT Feugiat Lorem Vladimir Fields (997)908-6102 2013/07/24 P.O. Box 609, 9056 Praesent Avenue Gresham OR Erat Zahir David (907)942-7793 2014/01/25 Ap #297-2286 Consequat St. Louisville KY Duis Cursus Consulting -------------------------------------------------------------------------------- /_old/Course materials/regular_expressions/phone-book-fun.py: -------------------------------------------------------------------------------- 1 | import re 2 | from phone_list import data 3 | 4 | 5 | def parse_phone_book(phone_book): 6 | for line in phone_book: 7 | if re.search(r'K.*Hardy', line['name']): 8 | print "{} - {}".format(line['name'], line["phone"]) 9 | 10 | parse_phone_book(data) 11 | -------------------------------------------------------------------------------- /_old/Course materials/regular_expressions/regex-groups.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | string = "My name is Michael Herman" 4 | 5 | # re.match(pattern, string, flags=0) 6 | m = re.match(r'(.*) name (.[s]?) .*', string) 7 | # m = re.match(r'(.*) name .[s]? (.*)', string) # what does this do? 8 | 9 | if m: 10 | print "group(0): ", m.group(0) 11 | print "group(1): ", m.group(1) 12 | print "group(2): ", m.group(2) 13 | else: 14 | print "Sorry. No match!!" 15 | -------------------------------------------------------------------------------- /_old/Course materials/regular_expressions/regex-namedgroups.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | string = "Michael Herman" 4 | 5 | # re.match(pattern, string, flags=0) 6 | m = re.match(r"(?P\w+)\W+(?P\w+)", string) 7 | 8 | if m: 9 | print "group(0) : ", m.group(0) 10 | print "group(1) : ", m.group(1) 11 | print "group(2) : ", m.group(2) 12 | print "" 13 | print 'group("first") : ', m.group("first") 14 | print 'group("last") : ', m.group("last") 15 | else: 16 | print "Sorry. No match!!" 17 | -------------------------------------------------------------------------------- /_old/Course materials/regular_expressions/regex-validation-refactor.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | validation = re.compile(r'[A-Za-z0-9.]+@[A-Za-z0-9.]+.com$') 4 | 5 | email = raw_input("Please enter your email address: ") 6 | 7 | while not validation.search(email): 8 | print "Please enter your email address correctly!" 9 | email = raw_input("Please enter your email address: ") 10 | 11 | print "\nYour email address is {}!".format(email) 12 | -------------------------------------------------------------------------------- /_old/Course materials/regular_expressions/regex-validation.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | validation = re.compile(r'[A-Za-zs.]') 4 | 5 | name = raw_input("Please enter your name: ") 6 | 7 | while not validation.search(name): 8 | print "Please enter your name correctly!" 9 | name = raw_input("Please enter your name: ") 10 | 11 | print "\nYour name is {}!".format(name) 12 | -------------------------------------------------------------------------------- /_old/Course materials/regular_expressions/regex_answers.txt: -------------------------------------------------------------------------------- 1 | 1. Blank lines - ^\s*\n 2 | 1. Spaces from the beginning of each line - ^\s+ 3 | 1. Bracketed numbers (e.g., '[1]') - \[\d+\] 4 | 1. The first column of numbers - ^\d+\s+ 5 | 1. 'Inc.', ', Inc.', 'Inc', and 'Incorporated' - (,* |,)(Incorporated|Inc\.*) 6 | 1. Space between the area code, '(XXX)', and the phone number, 'XXX-XXXX' - find - (\(\d{3}\))(\s)(\d{3}-\d{4}) then replace - $1$3 -------------------------------------------------------------------------------- /_old/Course materials/regular_expressions/regex_review.py: -------------------------------------------------------------------------------- 1 | # Modify the variable value so that all of the `print` statements return `True`. 2 | 3 | import re 4 | 5 | zero = "Python" 6 | one = "5/25/2014" 7 | two = "A88 8AA" 8 | three = '\w\d\w\s\w\d\w' 9 | four = "$4.76" 10 | five = ["haaaappy", "birthday"] 11 | six = r'\.(doc|odt)$' 12 | seven = "My email is (email redacted)" 13 | 14 | # zero = "Ruby" 15 | # one = "5/25/14" 16 | # two = "A99 9AA" 17 | # three = r'' 18 | # four = "6.76" 19 | # five = ["happy","birthday"] 20 | # six = r'\.(doc)$' 21 | # seven = "My email is michael@mherman.org" 22 | 23 | # DO NOT CHANGE ANYTHING BELOW THIS LINE # 24 | # -------------------------------------- # 25 | 26 | print "zero: {}".format( 27 | zero == re.search(r'[P].*', "This is Real Python").group()) 28 | print "one: {}".format( 29 | one == re.search(r'\d{1,2}\/\d{1,2}\/\d{4}', "5/25/2014").group()) 30 | print "two: {}".format( 31 | two == re.match( 32 | r'[A-Z]([A-Z](\d{1,2}|\d[A-Z])|\d{1,2})\s\d[A-Z]{2}', 33 | "A88 8AA", 34 | re.VERBOSE 35 | ).group() 36 | ) 37 | print "three: {}".format(bool(re.search(three, "B4c r79").group())) 38 | print "four: {}".format(bool(re.search(r'\$[0-5]\.\d\d', four))) 39 | print "five: {}".format(bool(re.search(r'\ha{4,10}ppy\b', five[0]))) 40 | files = ['test.doc', 'test.odt', 'test.ddt', 'doc', 'testodt', 'test.doc'] 41 | matched_files = [file for file in files if re.search(six, file)] 42 | print "six: {}".format(len(matched_files) == 3) 43 | email_regex = r'\w+@\w+\.(com|org|edu|net)' 44 | text = "My email is michael@mherman.org" 45 | redacted_text = re.sub(email_regex, '(email redacted)', text) 46 | print "seven: {}".format(seven == redacted_text) 47 | -------------------------------------------------------------------------------- /chp01/1-1.py: -------------------------------------------------------------------------------- 1 | # 1.1 review exercises 2 | 3 | 4 | ''' The following line won't run because of a syntax error ''' 5 | print("hi) 6 | 7 | # We didn't close the double quotes at the end of the string. 8 | # The line above needed to have been: 9 | # print("hi") 10 | 11 | 12 | ''' The following lines won't run properly, 13 | even if the syntax error in the line above is corrected, 14 | because of a run-time error ''' 15 | print(hello) 16 | 17 | # We meant to print the string "hello"; 18 | # a variable named 'hello' doesn't exist yet. 19 | # This line could have been: 20 | # myString = "hello" 21 | # print(myString) 22 | -------------------------------------------------------------------------------- /chp01/1-2.py: -------------------------------------------------------------------------------- 1 | # chapter 1 review exercises 2 | 3 | # The following lines can also be typed 4 | # directly into the interactive window as well: 5 | 6 | 7 | # display a string directly 8 | print("hello") 9 | 10 | 11 | # display the contents of a string variable 12 | my_string = "hi" 13 | print(my_string) 14 | -------------------------------------------------------------------------------- /chp03/3-1.py: -------------------------------------------------------------------------------- 1 | # 3.1 review exercises 2 | 3 | print('There are "double quotes" in this string.') 4 | 5 | print("This string's got an apostrophe.") 6 | 7 | print('''This string was written on multiple lines, 8 | and it displays across multiple lines''') 9 | 10 | print("This one-line string was written out \ 11 | using multiple lines") 12 | -------------------------------------------------------------------------------- /chp03/3-2.py: -------------------------------------------------------------------------------- 1 | # 3.2 review exercises 2 | 3 | 4 | # Display the number of letters in the string 5 | my_word = "antidisestablishmentarianism" 6 | print(len(my_word)) 7 | 8 | # Concatenate two strings together 9 | string_left = "bat" 10 | string_right = "man" 11 | print(string_left + string_right) 12 | 13 | # Display two strings together, with a space in between 14 | string_one = "heebie" 15 | string_two = "jeebies" 16 | print(string_one, string_two) 17 | 18 | 19 | # Use subscripting to display part of a string 20 | print("bazinga"[2:6]) 21 | 22 | 23 | # A more advanced way to do the above example would be: 24 | my_string = "bazinga" 25 | start_index = 2 26 | print(my_string[start_index:len(my_string) - start_index + 1]) 27 | -------------------------------------------------------------------------------- /chp03/3-3.py: -------------------------------------------------------------------------------- 1 | # 3.3 review exercises 2 | 3 | # Take input from the user and display that input back 4 | my_input = input("Type something: ") 5 | print(my_input) 6 | 7 | # Display the input string converted to lower-case letters 8 | print(my_input.lower()) 9 | -------------------------------------------------------------------------------- /chp03/first_letter.py: -------------------------------------------------------------------------------- 1 | # chapter 3 first_letter.py 2 | # Return the upper-case first letter entered by the user 3 | 4 | user_input = input("Tell me your password: ") 5 | first_letter = user_input[0] 6 | print("The first letter you entered was:", first_letter.upper()) 7 | -------------------------------------------------------------------------------- /chp04/4-1.py: -------------------------------------------------------------------------------- 1 | # 4.1 review exercises 2 | 3 | 4 | # Store an integer as a string 5 | my_integer_string = "6" 6 | 7 | # Convert the 'integer' string into an int object using int() 8 | # Multiply the integer by 7 and display the result 9 | print(int(my_integer_string) * 7) 10 | 11 | 12 | # Store a floating-point number as a string 13 | my_float_string = "6.01" 14 | 15 | # Convert the 'float' string into a number using float() 16 | # Multiply the number by 7 and display the result 17 | print(float(my_float_string) * 7) 18 | 19 | 20 | # Create a string and an int object, then display them together 21 | my_string = "mp" 22 | my_int = 3 23 | print(my_string + str(my_int)) 24 | -------------------------------------------------------------------------------- /chp04/4-2.py: -------------------------------------------------------------------------------- 1 | # 4.2 review exercises 2 | 3 | weight = 0.2 4 | animal = "newt" 5 | 6 | # Concatenate a number and a string in one print statement 7 | print(str(weight) + " kg is the weight of the newt.") 8 | 9 | # Use format() to print a number and a string inside of another string 10 | print("{} kg is the weight of the {}.".format(weight, animal)) 11 | 12 | # Use format() to add objects inside a string using index numbers 13 | # (Here we reversed the arguments - just because we could.) 14 | print("{1} kg is the weight of the {0}.".format(animal, weight)) 15 | 16 | # Use format() to print new objects inside a string 17 | print("{} kg is the weight of the {}.".format(0.2, "newt")) 18 | 19 | # Use formatted string literal to reference new objects inside a string 20 | print(f"{weight} kg is the weight of the {animal}.") 21 | -------------------------------------------------------------------------------- /chp04/4-3.py: -------------------------------------------------------------------------------- 1 | # 4.3 review exercises 2 | 3 | 4 | # Cannot find the string "a" in the string "AAA": 5 | print("AAA".find("a")) 6 | 7 | 8 | # Try to find a number inside a string; 9 | # use str() to convert the number first 10 | version = "version 2.0" 11 | v_num = 2.0 12 | print(version.find(str(v_num))) 13 | 14 | 15 | # Try to find an upper-case "X" in user input: 16 | my_input = input("Type something: ") 17 | print(my_input.find("X")) 18 | -------------------------------------------------------------------------------- /chp04/translate.py: -------------------------------------------------------------------------------- 1 | # chapter 4 translate.py 2 | # Turn a user's input into leetspeak 3 | 4 | my_text = input("Enter some text: ") 5 | 6 | my_text = my_text.replace("a", "4") 7 | my_text = my_text.replace("b", "8") 8 | my_text = my_text.replace("e", "3") 9 | my_text = my_text.replace("l", "1") 10 | my_text = my_text.replace("o", "0") 11 | my_text = my_text.replace("s", "5") 12 | my_text = my_text.replace("t", "7") 13 | 14 | print(my_text) 15 | -------------------------------------------------------------------------------- /chp05/5-1.py: -------------------------------------------------------------------------------- 1 | # 5.1 review exercises 2 | 3 | 4 | def cube(num): 5 | ''' Returns the cube of the input number ''' 6 | cube_num = num * num * num 7 | return cube_num 8 | 9 | print("0 cubed is", cube(0)) 10 | print("2 cubed is", cube(2)) 11 | 12 | 13 | def multiply(num1, num2): 14 | ''' Returns the result of multiplying two input numbers ''' 15 | return num1 * num2 16 | 17 | mult_result = multiply(2, 5) 18 | print("2 times 5 is", mult_result) 19 | -------------------------------------------------------------------------------- /chp05/5-2.py: -------------------------------------------------------------------------------- 1 | # 5.2 review exercises 2 | 3 | 4 | # print the integer 2 through 10 using a "for" loop 5 | for i in range(2, 11): 6 | print(i) 7 | 8 | 9 | # print the integer 2 through 10 using a "while" loop 10 | i = 2 11 | while (i < 11): 12 | print(i) 13 | i = i + 1 14 | 15 | 16 | def doubles(num): 17 | ''' Return the result of multiplying an input number by 2 ''' 18 | return num * 2 19 | 20 | # Call doubles to double the number 2 three times 21 | my_num = 2 22 | for i in range(0, 3): 23 | my_num = doubles(my_num) 24 | print(my_num) 25 | -------------------------------------------------------------------------------- /chp05/exponent.py: -------------------------------------------------------------------------------- 1 | # chapter 5 exponent.py 2 | # Receive two input numbers and calculate their power 3 | 4 | base = input("Enter a base: ") 5 | exponent = input("Enter an exponent: ") 6 | result = float(base) ** float(exponent) 7 | print("{} to the power of {} = {}".format(base, exponent, result)) 8 | -------------------------------------------------------------------------------- /chp05/invest.py: -------------------------------------------------------------------------------- 1 | # chapter 5 invest.py 2 | # calculate compound interest to track the growth of an investment 3 | 4 | 5 | def invest(amount, rate, time): 6 | print("principal amount: ${}".format(amount)) 7 | print("annual rate of return:", rate) 8 | for t in range(1, time + 1): 9 | amount = amount * (1 + rate) 10 | print("year {}: ${}".format(t, amount)) 11 | print() 12 | 13 | invest(100, .05, 8) 14 | invest(2000, .025, 5) 15 | -------------------------------------------------------------------------------- /chp05/temperature.py: -------------------------------------------------------------------------------- 1 | # chapter 5 temperature.py 2 | # Convert Celsius and Fahrenheit temperatures using functions 3 | 4 | 5 | def convert_cel_to_far(cel_temp): 6 | far_temp = cel_temp * 9 / 5 + 32 7 | return far_temp 8 | 9 | 10 | def convert_far_to_cel(far_temp): 11 | cel_temp = (far_temp - 32) * 5 / 9 12 | return cel_temp 13 | 14 | temp1 = 72 15 | print("{} degrees F = {} degrees C".format(temp1, convert_far_to_cel(temp1))) 16 | 17 | temp2 = 37 18 | print("{} degrees C = {} degrees F".format(temp2, convert_cel_to_far(temp2))) 19 | -------------------------------------------------------------------------------- /chp07/7-1.py: -------------------------------------------------------------------------------- 1 | # 7.1 review exercises 2 | 3 | 4 | # Test whether these expressions are True or False 5 | print(1 <= 1) 6 | print(1 != 1) 7 | print(1 != 2) 8 | print("good" != "bad") 9 | print("good" != "Good") 10 | print(123 == "123") 11 | -------------------------------------------------------------------------------- /chp07/7-2.py: -------------------------------------------------------------------------------- 1 | # 7.2 review exercises 2 | 3 | 4 | # Test whether these expressions are True or False 5 | print((1 <= 1) and (1 != 1)) 6 | print(not (1 != 2)) 7 | print(("good" != "bad") or False) 8 | print(("good" != "Good") and not (1 == 1)) 9 | -------------------------------------------------------------------------------- /chp07/7-3.py: -------------------------------------------------------------------------------- 1 | # 7.3 review exercises 2 | 3 | 4 | # Display whether the length of user input is <, > or = 5 characters 5 | my_input = input("Type something: ") 6 | 7 | if len(my_input) < 5: 8 | print("Your input is less than 5 characters long.") 9 | elif len(my_input) > 5: 10 | print("Your input is greater than 5 characters long.") 11 | else: 12 | print("Your input is 5 characters long.") 13 | -------------------------------------------------------------------------------- /chp07/7-4.py: -------------------------------------------------------------------------------- 1 | # 7.4 review exercises 2 | 3 | 4 | # Run in an infinite loop until the user types "q" or "Q" 5 | while True: 6 | my_input = input('Type "q" or "Q" to quit: ') 7 | if my_input.upper() == "Q": 8 | break 9 | 10 | # Display every number from 1 through 50 except multiples of 3 11 | for i in range(1, 51): 12 | if i % 3 == 0: 13 | continue 14 | print(i) 15 | -------------------------------------------------------------------------------- /chp07/7-5.py: -------------------------------------------------------------------------------- 1 | # 7.5 review exercises 2 | 3 | 4 | # Ask the user to enter an integer. 5 | # Repeat the process if the user hasn't entered an integer. 6 | repeat = True 7 | while repeat: 8 | try: 9 | my_input = input("Type an integer: ") 10 | print(int(my_input)) 11 | repeat = False 12 | except ValueError: 13 | print("try again") 14 | -------------------------------------------------------------------------------- /chp07/7-6.py: -------------------------------------------------------------------------------- 1 | # 7.6 review exercises 2 | 3 | from random import randint 4 | 5 | 6 | # Simulate the toss of a die 7 | print(randint(1, 6)) 8 | 9 | 10 | # Simulate 10,000 throws of dice and display the average result 11 | trials = 10000 12 | total = 0 13 | for trial in range(0, trials): 14 | total += randint(1, 6) 15 | avg_result = total / trials 16 | print("The average result of {} throws was {}".format(trials, avg_result)) 17 | -------------------------------------------------------------------------------- /chp07/coin_toss.py: -------------------------------------------------------------------------------- 1 | # chapter 7 coin_toss.py 2 | # Simulate the results of a series of coin tosses and track the results 3 | 4 | from random import randint 5 | 6 | flips = 0 7 | trials = 10000 8 | 9 | for trial in range(0, trials): 10 | flips += 1 # first flip 11 | if randint(0, 1) == 0: # flipped tails on first flip 12 | while randint(0, 1) == 0: # keep flipping tails 13 | flips += 1 14 | flips += 1 # finally flipped heads 15 | else: # otherwise, flipped heads on first flip 16 | while randint(0, 1) == 1: # keep flipping heads 17 | flips += 1 18 | flips += 1 # finally flipped tails 19 | 20 | print(flips / trials) 21 | -------------------------------------------------------------------------------- /chp07/coin_toss_alternative.py: -------------------------------------------------------------------------------- 1 | # chapter 7 coin_toss_alternative.py 2 | # Simulate the results of a series of coin tosses and track the results 3 | 4 | from random import randint 5 | 6 | 7 | trials = 100000 8 | flips = 0 9 | 10 | for trial in range(1, trials): 11 | first_flip = randint(0, 1) 12 | flips += 1 13 | while randint(0, 1) == first_flip: 14 | flips += 1 15 | flips += 1 16 | 17 | print("The average number of coin flips was {0}".format(flips / trials)) 18 | -------------------------------------------------------------------------------- /chp07/coin_toss_functions.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | 4 | def single_trial(): 5 | toss = randint(0, 1) 6 | total_flips = 1 7 | 8 | while toss == randint(0, 1): 9 | total_flips += 1 10 | toss = randint(0, 1) 11 | 12 | total_flips += 1 13 | return total_flips 14 | 15 | 16 | def flip_trial_avg(num_trials): 17 | total = 0 18 | for trial in range(num_trials): 19 | total += single_trial() 20 | return total / num_trials 21 | 22 | print("The average number of coin flips was {0}".format(flip_trial_avg(10000))) 23 | -------------------------------------------------------------------------------- /chp07/election.py: -------------------------------------------------------------------------------- 1 | # chapter 7 election.py 2 | # Simulate the results of an election using a Monte Carlo simulation 3 | 4 | from random import random 5 | 6 | total_A_wins = 0 7 | total_B_wins = 0 8 | 9 | trials = 100000 10 | for trial in range(0, trials): 11 | A_win = 0 12 | B_win = 0 13 | if random() < .87: # 1st region 14 | A_win += 1 15 | else: 16 | B_win += 1 17 | if random() < .65: # 2nd region 18 | A_win += 1 19 | else: 20 | B_win += 1 21 | if random() < .17: # 3rd region 22 | A_win += 1 23 | else: 24 | B_win += 1 25 | # determine overall election outcome 26 | if A_win > B_win: 27 | total_A_wins += 1 28 | else: 29 | total_B_wins += 1 30 | 31 | print("Probability A wins:", total_A_wins / trials) 32 | print("Probability B wins:", total_B_wins / trials) 33 | -------------------------------------------------------------------------------- /chp07/factors.py: -------------------------------------------------------------------------------- 1 | # chapter 7 factors.py 2 | # display all the factors of a number chosen by the user 3 | 4 | num = int(input("Enter a positive integer: ")) 5 | for divisor in range(1, num + 1): 6 | if num % divisor == 0: 7 | print("{} is a divisor of {}".format(divisor, num)) 8 | -------------------------------------------------------------------------------- /chp08/8-1.py: -------------------------------------------------------------------------------- 1 | # 8.1 review exercises 2 | 3 | 4 | desserts = ["ice cream", "cookies"] 5 | 6 | # Sort the desserts list alphabetically 7 | desserts.sort() 8 | 9 | # Display the sorted list 10 | print(desserts) 11 | 12 | # Display the index value of "ice cream" 13 | print(desserts.index("ice cream")) 14 | 15 | # Copy the contents of the "desserts" list into a new "food" list 16 | food = desserts[:] 17 | 18 | # Add some food to the list 19 | food.append("broccoli") 20 | food.append("turnips") 21 | 22 | # Display the contents of both lists 23 | print(desserts) 24 | print(food) 25 | 26 | # Take "cookies" out of the "food" list 27 | food.remove("cookies") 28 | 29 | # Display the first two items in the "food" list 30 | print(food[0:2]) 31 | 32 | # Create a "breakfast" list full of cookies and display it 33 | my_breakfast = "cookies, cookies, cookies" 34 | breakfast = my_breakfast.split(", ") 35 | print(breakfast) 36 | 37 | """ 38 | Define a function that takes a list of numbers, `[2, 4, 8, 16, 32, 64]`, as the 39 | argument and then outputs only the numbers from the list that fall between 1 40 | and 20 (inclusive) 41 | """ 42 | 43 | 44 | def print_list(list_of_nums): 45 | for num in list_of_nums: 46 | if num >= 2 and num <= 20: 47 | print(num) 48 | 49 | list_of_numbers = [2, 4, 8, 16, 32, 64] 50 | print_list(list_of_numbers) 51 | -------------------------------------------------------------------------------- /chp08/8-2.py: -------------------------------------------------------------------------------- 1 | # 8.2 review exercises 2 | 3 | 4 | # Create a tuple "cardinal_nums" with "first", "second" and "third" 5 | cardinal_nums = ("first", "second", "third") 6 | 7 | # Display the second object in the tuple 8 | print(cardinal_nums[1]) 9 | 10 | 11 | # unpack the tuple into three string and display them 12 | pos1, pos2, pos3 = cardinal_nums 13 | print(pos1) 14 | print(pos2) 15 | print(pos3) 16 | -------------------------------------------------------------------------------- /chp08/8-3.py: -------------------------------------------------------------------------------- 1 | # 8.3 review exercises 2 | 3 | 4 | # Create an empty dictionary 5 | birthdays = {} 6 | 7 | # Add some key-value pairs to the dictionary 8 | birthdays["Luke Skywalker"] = "5/25/19" 9 | birthdays["Obi-Wan Kenobi"] = "3/11/57" 10 | birthdays["Darth Vader"] = "4/1/41" 11 | 12 | # Check if "Yoda" and "Darth Vader exist; if not, add them 13 | if "Yoda" not in birthdays: 14 | birthdays["Yoda"] = "unknown" 15 | if "Darth Vader" not in birthdays: 16 | birthdays["Darth Vader"] = "unknown" 17 | 18 | # Bonus points: you could instead loop over a list of names to check 19 | # for name in ["Yoda", "Darth Vader"]: 20 | # if not name in birthdays: 21 | # birthdays[name] = "unknown" 22 | 23 | # Display the contents of the dictionary, one pair at a time 24 | for name in birthdays: 25 | print(name, birthdays[name]) 26 | 27 | # Remove "Darth Vader" 28 | del(birthdays["Darth Vader"]) 29 | print(birthdays) 30 | 31 | 32 | # Bonus: could have created dictionary by passing a list to dict() 33 | birthdays = dict([("Luke Skywalker", "5/25/19"), 34 | ("Obi-Wan Kenobi", "3/11/57"), 35 | ("Darth Vader", "4/1/41")]) 36 | -------------------------------------------------------------------------------- /chp08/capital_city_loop.py: -------------------------------------------------------------------------------- 1 | from capitals import capitals_dict 2 | import random 3 | 4 | 5 | def capital_game(state, capital): 6 | while True: 7 | guess = input("What is the capital of '{}'? ".format(state)).lower() 8 | if guess == "exit": 9 | print("The capital of '{}' is '{}'.".format(state, capital)) 10 | print("Goodbye") 11 | break 12 | elif guess == (capital).lower(): 13 | print("Correct! Nice job.") 14 | break 15 | 16 | 17 | state = random.choice(list(capitals_dict.keys())) 18 | capital = capitals_dict[state] 19 | capital_game(state, capital) 20 | -------------------------------------------------------------------------------- /chp08/capitals.py: -------------------------------------------------------------------------------- 1 | capitals_dict = { 2 | 'Alabama': 'Montgomery', 3 | 'Alaska': 'Juneau', 4 | 'Arizona': 'Phoenix', 5 | 'Arkansas': 'Little Rock', 6 | 'California': 'Sacramento', 7 | 'Colorado': 'Denver', 8 | 'Connecticut': 'Hartford', 9 | 'Delaware': 'Dover', 10 | 'Florida': 'Tallahassee', 11 | 'Georgia': 'Atlanta', 12 | 'Hawaii': 'Honolulu', 13 | 'Idaho': 'Boise', 14 | 'Illinois': 'Springfield', 15 | 'Indiana': 'Indianapolis', 16 | 'Iowa': 'Des Moines', 17 | 'Kansas': 'Topeka', 18 | 'Kentucky': 'Frankfort', 19 | 'Louisiana': 'Baton Rouge', 20 | 'Maine': 'Augusta', 21 | 'Maryland': 'Annapolis', 22 | 'Massachusetts': 'Boston', 23 | 'Michigan': 'Lansing', 24 | 'Minnesota': 'Saint Paul', 25 | 'Mississippi': 'Jackson', 26 | 'Missouri': 'Jefferson City', 27 | 'Montana': 'Helena', 28 | 'Nebraska': 'Lincoln', 29 | 'Nevada': 'Carson City', 30 | 'New Hampshire': 'Concord', 31 | 'New Jersey': 'Trenton', 32 | 'New Mexico': 'Santa Fe', 33 | 'New York': 'Albany', 34 | 'North Carolina': 'Raleigh', 35 | 'North Dakota': 'Bismarck', 36 | 'Ohio': 'Columbus', 37 | 'Oklahoma': 'Oklahoma City', 38 | 'Oregon': 'Salem', 39 | 'Pennsylvania': 'Harrisburg', 40 | 'Rhode Island': 'Providence', 41 | 'South Carolina': 'Columbia', 42 | 'South Dakota': 'Pierre', 43 | 'Tennessee': 'Nashville', 44 | 'Texas': 'Austin', 45 | 'Utah': 'Salt Lake City', 46 | 'Vermont': 'Montpelier', 47 | 'Virginia': 'Richmond', 48 | 'Washington': 'Olympia', 49 | 'West Virginia': 'Charleston', 50 | 'Wisconsin': 'Madison', 51 | 'Wyoming': 'Cheyenne', 52 | } 53 | -------------------------------------------------------------------------------- /chp08/cats_with_hats.py: -------------------------------------------------------------------------------- 1 | def get_cats_with_hats(array_of_cats): 2 | cats_with_hats_on = [] 3 | for num in range(1, 100 + 1): 4 | for cat in range(1, 100 + 1): 5 | if cat % num == 0: 6 | if array_of_cats[cat] is True: 7 | array_of_cats[cat] = False 8 | else: 9 | array_of_cats[cat] = True 10 | for cat in range(1, 100 + 1): 11 | if cats[cat] is True: 12 | cats_with_hats_on.append(cat) 13 | return cats_with_hats_on 14 | 15 | cats = [False] * (100 + 1) 16 | print(get_cats_with_hats(cats)) 17 | -------------------------------------------------------------------------------- /chp08/cats_with_hats_alternative.py: -------------------------------------------------------------------------------- 1 | number_of_cats = 100 2 | cats_with_hats = [] 3 | number_of_laps = 100 4 | 5 | # We want the laps to be from 1 to 100 instead of 0 to 99 6 | for lap in range(1, number_of_laps + 1): 7 | for cat in range(1, number_of_cats + 1): 8 | 9 | # Only look at cats that are divisible by the lap 10 | if cat % lap == 0: 11 | if cat in cats_with_hats: 12 | cats_with_hats.remove(cat) 13 | else: 14 | cats_with_hats.append(cat) 15 | 16 | print(cats_with_hats) 17 | -------------------------------------------------------------------------------- /chp08/cats_with_hats_dict.py: -------------------------------------------------------------------------------- 1 | theCats = {} 2 | 3 | for i in range(1, 101): 4 | theCats[i] = False 5 | 6 | for i in range(1, 101): 7 | for cats, hats in theCats.items(): 8 | if cats % i == 0: 9 | if theCats[cats]: 10 | theCats[cats] = False 11 | else: 12 | theCats[cats] = True 13 | 14 | for cats, hats in theCats.items(): 15 | if theCats[cats]: 16 | print("Cat {} has a hat.".format(cats)) 17 | else: 18 | print("Cat {} is hatless!".format(cats)) 19 | -------------------------------------------------------------------------------- /chp09/practice_files/backup/images/additional files/one last image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/backup/images/additional files/one last image.png -------------------------------------------------------------------------------- /chp09/practice_files/backup/images/an image file.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/backup/images/an image file.gif -------------------------------------------------------------------------------- /chp09/practice_files/backup/images/another image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/backup/images/another image.gif -------------------------------------------------------------------------------- /chp09/practice_files/backup/images/one more image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/backup/images/one more image.gif -------------------------------------------------------------------------------- /chp09/practice_files/backup/images/png file - not a gif.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/backup/images/png file - not a gif.png -------------------------------------------------------------------------------- /chp09/practice_files/backup/little pics/better not delete me.txt: -------------------------------------------------------------------------------- 1 | hi mom -------------------------------------------------------------------------------- /chp09/practice_files/backup/little pics/look in here too/definitely has to go.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/backup/little pics/look in here too/definitely has to go.jpg -------------------------------------------------------------------------------- /chp09/practice_files/backup/little pics/save me please.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/backup/little pics/save me please.jpg -------------------------------------------------------------------------------- /chp09/practice_files/backup/little pics/to be deleted.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/backup/little pics/to be deleted.jpg -------------------------------------------------------------------------------- /chp09/practice_files/example.txt: -------------------------------------------------------------------------------- 1 | Hi there. 2 | This is a simple text file. 3 | If you can read me, congratulations! -------------------------------------------------------------------------------- /chp09/practice_files/images/additional files/one last image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/images/additional files/one last image.png -------------------------------------------------------------------------------- /chp09/practice_files/images/an image file.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/images/an image file.gif -------------------------------------------------------------------------------- /chp09/practice_files/images/another image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/images/another image.gif -------------------------------------------------------------------------------- /chp09/practice_files/images/one more image.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/images/one more image.gif -------------------------------------------------------------------------------- /chp09/practice_files/images/png file - not a gif.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/images/png file - not a gif.png -------------------------------------------------------------------------------- /chp09/practice_files/little pics/better not delete me.txt: -------------------------------------------------------------------------------- 1 | hi mom -------------------------------------------------------------------------------- /chp09/practice_files/little pics/look in here too/definitely has to go.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/little pics/look in here too/definitely has to go.jpg -------------------------------------------------------------------------------- /chp09/practice_files/little pics/save me please.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/little pics/save me please.jpg -------------------------------------------------------------------------------- /chp09/practice_files/little pics/to be deleted.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp09/practice_files/little pics/to be deleted.jpg -------------------------------------------------------------------------------- /chp09/practice_files/pastimes.csv: -------------------------------------------------------------------------------- 1 | Person,Favorite pastime 2 | Fezzik,Fighting 3 | Westley,Winning 4 | Inigo Montoya,Sword fighting 5 | Buttercup,Complaining 6 | -------------------------------------------------------------------------------- /chp09/practice_files/poem.txt: -------------------------------------------------------------------------------- 1 | This is the first line 2 | The second line is longer 3 | Hippopotamus -------------------------------------------------------------------------------- /chp09/practice_files/scores.csv: -------------------------------------------------------------------------------- 1 | LLCoolDave,23 2 | LLCoolDave,27 3 | red,12 4 | LLCoolDave,26 5 | tom123,26 6 | O_O,7 7 | Misha46,24 8 | O_O,14 9 | Empiro,18 10 | Empiro,18 11 | MaxxT,25 12 | L33tH4x,42 13 | Misha46,25 14 | johnsmith,30 15 | Empiro,23 16 | O_O,22 17 | MaxxT,25 18 | Misha46,24 19 | -------------------------------------------------------------------------------- /chp09/practice_files/tabbed wonka.csv: -------------------------------------------------------------------------------- 1 | First name Last name Reward 2 | Charlie Bucket golden ticket, chocolate factory 3 | Veruca Salt squirrel revolution 4 | Violet Beauregarde fruit chew 5 | -------------------------------------------------------------------------------- /chp09/practice_files/wonka.csv: -------------------------------------------------------------------------------- 1 | First name,Last name,Reward 2 | Charlie,Bucket,"golden ticket, chocolate factory" 3 | Veruca,Salt,squirrel revolution 4 | Violet,Beauregarde,fruit chew 5 | -------------------------------------------------------------------------------- /chp09/solutions/9-1.py: -------------------------------------------------------------------------------- 1 | # 9.1 review exercises 2 | 3 | 4 | ''' 5 | In order to run correctly, this script first needs to 6 | be placed in the Chapter 10 "practice_files" folder. 7 | (File paths are covered in section 10.2) 8 | ''' 9 | 10 | # Read a text file by looping over individual lines 11 | my_poem = open("poem.txt", "r") 12 | for line in my_poem.readlines(): 13 | # Replace automatic line break at end of line; 14 | # file already contains newline characters 15 | print(line,) 16 | my_poem.close() 17 | 18 | # Print some blank lines to separate the two examples 19 | print("\n\n") 20 | 21 | # Use "with" to automatically close a file when finished 22 | with open("poem.txt", "r") as my_poem: 23 | for line in my_poem.readlines(): 24 | print(line,) 25 | 26 | # Write the contents of one file into another, line-by-line 27 | poem_in = open("poem.txt", "r") 28 | poem_out = open("output.txt", "w") 29 | for line in poem_in.readlines(): 30 | poem_out.write(line) 31 | poem_in.close() 32 | poem_out.close() 33 | 34 | # Repeat the previous exercise using the "with" keyword 35 | # (This will overwrite the previous output file.) 36 | with open("poem.txt", "r") as poem_in, open("output.txt", "w") as poem_out: 37 | for line in poem_in.readlines(): 38 | poem_out.write(line) 39 | 40 | 41 | # Append a new line to the end of "output.txt" 42 | # (Need to start on a new line, so add "\n" to the beginning.) 43 | with open("output.txt", "a") as poem_append: 44 | poem_append.write("\nThus ends the haiku.") 45 | -------------------------------------------------------------------------------- /chp09/solutions/9-2.py: -------------------------------------------------------------------------------- 1 | # 9.2 review exercises 2 | 3 | 4 | # Initial setup 5 | import os 6 | import glob 7 | # This path may need to be changed depending on your setup 8 | path = "C:/Real Python/refactor/chp10/practice_files/images" 9 | 10 | 11 | # Display the full paths of all files and folders in the main "images" folder 12 | print('Full contents of "images" folder:') 13 | for file_name in os.listdir(path): 14 | print(os.path.join(path, file_name)) 15 | 16 | # Display the full paths of any PNG files in the "images" folder 17 | file_matches = os.path.join(path, "*.png") 18 | print('All PNG files in "images" folder:') 19 | for file_name in glob.glob(file_matches): 20 | print(file_name) 21 | 22 | # Change all PNGs to JPGs in the "images" folder and its subfolders 23 | # Could use indexing to get the file extension, but try using os.path.splitext() 24 | for current_folder, subfolders, file_names in os.walk(path): 25 | for file_name in file_names: 26 | file_path = os.path.join(current_folder, file_name) 27 | file_tuple = os.path.splitext(file_path) # split into (path, extension) 28 | if file_tuple[1].lower() == ".png": # check if extension is PNG 29 | pass # os.rename(file_path, file_tuple[0] + ".jpg") 30 | 31 | # Check that the two files have been converted to JPGs successfully 32 | print(os.path.exists(os.path.join(path, "png file - not a gif.jpg"))) 33 | print(os.path.exists(os.path.join(path, "additional files/one last image.jpg"))) 34 | -------------------------------------------------------------------------------- /chp09/solutions/9-3.py: -------------------------------------------------------------------------------- 1 | # 9.3 review exercises 2 | 3 | 4 | # Initial setup 5 | import os 6 | import csv 7 | # This path may need to be changed depending on your setup 8 | path = "C:/Real Python/refactor/chp10/practice_files" 9 | 10 | 11 | # Read in a CSV and display each row except the header row 12 | # Append a third column and write out the resulting CSV with a new header 13 | in_file_path = os.path.join(path, "pastimes.csv") 14 | out_file_path = os.path.join(path, "Output/categorized pastimes.csv") 15 | with open(in_file_path, "rb") as inFile, open(out_file_path, "wb") as outFile: 16 | csv_reader = csv.reader(inFile) 17 | csv_writer = csv.writer(outFile) 18 | 19 | # skip header row and write a new output header row 20 | csv_reader.next() 21 | csv_writer.writerow(["Name", "Favorite Pastime", "Type of pastime"]) 22 | 23 | for row in csv_reader: 24 | print row 25 | # Check if "Favorite Pastime" includes "fighting" 26 | if row[1].lower().find("fighting") != -1: 27 | row.append("Combat") 28 | else: 29 | row.append("Other") 30 | # Add the new row to the output 31 | csv_writer.writerow(row) 32 | -------------------------------------------------------------------------------- /chp09/solutions/high_scores.py: -------------------------------------------------------------------------------- 1 | # chapter 9 high_scores.py 2 | # Read in CSV data containing names and scores; display a high score list 3 | 4 | import csv 5 | import os 6 | my_path = "C:/Real Python/refactor/chp10/practice_files" 7 | 8 | high_scores_dict = {} 9 | with open(os.path.join(my_path, "scores.csv"), "rb") as myFile: 10 | my_file_reader = csv.reader(myFile) 11 | for name, score in my_file_reader: # get each name/score pair 12 | score = int(score) # convert string score to integer 13 | if name in high_scores_dict: # already had an entry for that name 14 | if score > high_scores_dict[name]: # new score is higher 15 | high_scores_dict[name] = score 16 | else: # haven't seen this name yet; add it to dictionary 17 | high_scores_dict[name] = score 18 | 19 | for name in sorted(high_scores_dict): 20 | print name, high_scores_dict[name] 21 | -------------------------------------------------------------------------------- /chp09/solutions/remove_files.py: -------------------------------------------------------------------------------- 1 | # chapter 9 remove_files.py 2 | # Remove JPG files from multiple folders based on file size 3 | 4 | import os 5 | 6 | path = "C:/Real Python/refactor/chp10/practice_files/little pics" 7 | for current_folder, subfolders, file_names in os.walk(path): 8 | for file_name in file_names: 9 | full_path = os.path.join(current_folder, file_name) 10 | # check if file is a JPG 11 | check_JPG = file_name.lower().endswith(".jpg") 12 | # check if size is less than 2Kb 13 | check_size = os.path.getsize(full_path) < 2000 14 | if check_JPG and check_size: # both conditions must be True 15 | print('Deleting "{}"...'.format(file_name)) 16 | os.remove(full_path) 17 | -------------------------------------------------------------------------------- /chp11/practice_files/Emperor cover sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp11/practice_files/Emperor cover sheet.pdf -------------------------------------------------------------------------------- /chp11/practice_files/Pride and Prejudice.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp11/practice_files/Pride and Prejudice.pdf -------------------------------------------------------------------------------- /chp11/practice_files/The Emperor.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp11/practice_files/The Emperor.pdf -------------------------------------------------------------------------------- /chp11/practice_files/The Whistling Gypsy.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp11/practice_files/The Whistling Gypsy.pdf -------------------------------------------------------------------------------- /chp11/practice_files/Walrus.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp11/practice_files/Walrus.pdf -------------------------------------------------------------------------------- /chp11/practice_files/half and half.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp11/practice_files/half and half.pdf -------------------------------------------------------------------------------- /chp11/practice_files/top secret.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp11/practice_files/top secret.pdf -------------------------------------------------------------------------------- /chp11/practice_files/ugly.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/realpython/book1-exercises/ff8c8c90925114a7ae9af219d9d95e4cce02a5ec/chp11/practice_files/ugly.pdf -------------------------------------------------------------------------------- /chp11/solutions/11-1.py: -------------------------------------------------------------------------------- 1 | # 11.1 review exercises 2 | 3 | 4 | import os 5 | from pyPdf import PdfFileReader, PdfFileWriter 6 | 7 | path = "C:/Real Python/refactor/chp12/practice_files" 8 | input_file_name = os.path.join(path, "The Whistling Gypsy.pdf") 9 | input_file = PdfFileReader(open(input_file_name, "rb")) 10 | 11 | # Display meta-data about file 12 | print("Title:", input_file.getDocumentInfo().title) 13 | print("Author:", input_file.getDocumentInfo().author) 14 | print("Number of pages:", input_file.getNumPages()) 15 | 16 | # Specify and open output text file 17 | output_file_name = os.path.join(path, "Output/The Whistling Gypsy.txt") 18 | with open(output_file_name, "w") as output_file: 19 | # Extract every page of text 20 | for page_num in range(0, input_file.getNumPages()): 21 | text = input_file.getPage(page_num).extractText() 22 | text = text.encode("utf-8") # convert text to unicode 23 | output_file.write(text) 24 | 25 | # Save file without cover page 26 | output_PDF = PdfFileWriter() 27 | for page_num in range(1, input_file.getNumPages()): 28 | output_PDF.addPage(input_file.getPage(page_num)) 29 | 30 | output_file_name = os.path.join(path, "Output/The Whistling Gypsy un-covered.pdf") 31 | with open(output_file_name, "wb") as output_file: 32 | output_PDF.write(output_file) 33 | -------------------------------------------------------------------------------- /chp11/solutions/11-2.py: -------------------------------------------------------------------------------- 1 | # 11.2 review exercises 2 | 3 | import os 4 | import copy 5 | from pyPdf import PdfFileReader, PdfFileWriter 6 | 7 | path = "C:/Real Python/refactor/chp12/practice_files" 8 | input_file_name = os.path.join(path, "Walrus.pdf") 9 | input_file = PdfFileReader(open(input_file_name, "rb")) 10 | output_PDF = PdfFileWriter() 11 | 12 | input_file.decrypt("IamtheWalrus") # decrypt the input file 13 | 14 | for page_num in range(0, input_file.getNumPages()): 15 | # rotate pages (call everything page_left for now; will make a copy) 16 | page_left = input_file.getPage(page_num) 17 | page_left.rotateCounterClockwise(90) 18 | 19 | page_right = copy.copy(page_left) # split each page in half 20 | upper_right = page_left.mediaBox.upperRight # get original page corner 21 | 22 | # crop and add left-side page 23 | page_left.mediaBox.upperRight = (upper_right[0] / 2, upper_right[1]) 24 | output_PDF.addPage(page_left) 25 | # crop and add right-side page 26 | page_right.mediaBox.upperLeft = (upper_right[0] / 2, upper_right[1]) 27 | output_PDF.addPage(page_right) 28 | 29 | # save new pages to an output file 30 | output_file_name = os.path.join(path, "Output/Updated Walrus.pdf") 31 | with open(output_file_name, "wb") as output_file: 32 | output_PDF.write(output_file) 33 | -------------------------------------------------------------------------------- /chp11/solutions/cover_the_emperor.py: -------------------------------------------------------------------------------- 1 | # chapter 11 cover_the_emperor.py 2 | # Add a cover sheet to a PDF; save the full output as a new PDF 3 | 4 | import os 5 | from pyPdf import PdfFileReader, PdfFileWriter 6 | 7 | path = "C:/Real Python/Course materials/Chapter 12/Practice files" 8 | input_file_name1 = os.path.join(path, "Emperor cover sheet.pdf") 9 | input_file1 = PdfFileReader(file(input_file_name1, "rb")) 10 | input_file_name2 = os.path.join(path, "The Emperor.pdf") 11 | input_file2 = PdfFileReader(file(input_file_name2, "rb")) 12 | output_PDF = PdfFileWriter() 13 | 14 | # Read in all pages from the cover sheet PDF file 15 | for page_num in range(0, input_file1.getNumPages()): 16 | page = input_file1.getPage(page_num) 17 | output_PDF.addPage(page) 18 | 19 | # Read in all pages from "The Emperor.pdf" into the same output file 20 | for page_num in range(0, input_file2.getNumPages()): 21 | page = input_file2.getPage(page_num) 22 | output_PDF.addPage(page) 23 | 24 | # Output the results into a new PDF 25 | output_file_name = os.path.join(path, "Output/The Covered Emperor.pdf") 26 | output_file = file(output_file_name, "wb") 27 | output_PDF.write(output_file) 28 | output_file.close() 29 | -------------------------------------------------------------------------------- /chp12/12-1.py: -------------------------------------------------------------------------------- 1 | # 12.1 review exercises 2 | 3 | import sqlite3 4 | 5 | # Create a temporary database connection in RAM 6 | with sqlite3.connect(':memory:') as connection: 7 | c = connection.cursor() 8 | 9 | # Create a "Roster" table with Name, Species and IQ fields 10 | c.execute("CREATE TABLE Roster(Name TEXT, Species TEXT, IQ INT)") 11 | 12 | # Add some data into the database 13 | roster_data = ( 14 | ("Jean-Baptiste Zorg", "Human", 122), 15 | ("Korben Dallas", "Meat Popsicle", 100), 16 | ("Ak'not", "Mangalore", -5) 17 | ) 18 | c.executemany("INSERT INTO Roster VALUES(?, ?, ?)", roster_data) 19 | 20 | # Update the Species of Korben Dallas to "Human" 21 | c.execute("UPDATE Roster SET Species=? WHERE Name=?", 22 | ('Human', 'Korben Dallas')) 23 | 24 | # Display the names and IQs of everyone classified as Human 25 | c.execute("SELECT Name, IQ FROM Roster WHERE Species = 'Human'") 26 | for row in c.fetchall(): 27 | print(row) 28 | -------------------------------------------------------------------------------- /chp13/13-1.py: -------------------------------------------------------------------------------- 1 | # 13.1 review exercises 2 | 3 | from urllib.request import urlopen 4 | 5 | # Get the full HTML from the "dionysus" page 6 | my_address = "https://realpython.com/practice/dionysus.html" 7 | html_page = urlopen(my_address) 8 | html_text = html_page.read().decode('utf-8') 9 | 10 | # Get the "Name" and "Favorite Color" using find() 11 | for tag in ["Name: ", "Favorite Color: "]: 12 | tag_start = html_text.find(tag) + len(tag) 13 | tag_end = html_text[tag_start:].find("<") 14 | # Remove extra spaces and newline padding 15 | print(html_text[tag_start:tag_start + tag_end].strip(" \n")) 16 | 17 | 18 | # Get the "Name" and "Favorite Color" using regular expressions 19 | import re 20 | # Match anything up until a new line or HTML tag; non-greedy 21 | for tag in ["Name: .*?[\n<]", "Favorite Color: .*?[\n<]"]: 22 | match_results = re.search(tag, html_text) 23 | # Remove the "Name: " or "Favorite Color: " label from first result 24 | result = re.sub(".*: ", "", match_results.group()) 25 | # Remove extra spaces and newline padding along with opening HTML tag 26 | print(result.strip(" \n<")) 27 | -------------------------------------------------------------------------------- /chp13/13-2.py: -------------------------------------------------------------------------------- 1 | # 13.2 review exercises 2 | 3 | from urllib.request import urlopen 4 | from bs4 import BeautifulSoup 5 | 6 | # Get the full HTML from the "profiles" page 7 | base_URL = "https://realpython.com/practice/" 8 | address = base_URL + "profiles.html" 9 | html_page = urlopen(address) 10 | html_text = html_page.read().decode('utf-8') 11 | soup = BeautifulSoup(html_text) 12 | 13 | # Parse out all the values of the page links 14 | for anchor in soup.find_all("a"): 15 | # Could also have used urlparse.urljoin() to get absolute URL 16 | link_address = base_URL + anchor["href"] 17 | # Display the text in the HTML page of each link 18 | link_page = urlopen(link_address) 19 | link_text = link_page.read().decode('utf-8') 20 | link_soup = BeautifulSoup(link_text) 21 | print(link_soup.get_text()) 22 | -------------------------------------------------------------------------------- /chp13/13-3.py: -------------------------------------------------------------------------------- 1 | # 13.3 review exercises 2 | 3 | import mechanicalsoup 4 | 5 | my_browser = mechanicalsoup.Browser() 6 | login_page = my_browser.get("https://realpython.com/practice/login.php") 7 | login_html = login_page.soup 8 | 9 | # select the form and fill in the input fields 10 | form = login_html.form 11 | form.select("input")[0]["value"] = "zeus" 12 | form.select("input")[1]["value"] = "ThunderDude" 13 | 14 | # submit form and show profile page title 15 | profiles_page = my_browser.submit(form, login_page.url) 16 | title = profiles_page.soup.title 17 | print("Title: ", title.text) 18 | 19 | # navigate back to login page and show title 20 | login_page = my_browser.get("https://realpython.com/practice/login.php") 21 | login_title = login_page.soup.title 22 | print("Title: ", login_title.text) 23 | 24 | # submit form with incorrect values 25 | form = login_html.form 26 | form.select("input")[0]["value"] = "wrong" 27 | form.select("input")[1]["value"] = "password" 28 | error_page = my_browser.submit(form, login_page.url) # submit form 29 | 30 | # check for string 31 | if error_page.soup.text.find("Wrong username or password!") != -1: 32 | print("Login Failed.") 33 | else: 34 | print("Login Successful.") 35 | -------------------------------------------------------------------------------- /chp13/13-4.py: -------------------------------------------------------------------------------- 1 | # 13.4 review exercises 2 | 3 | from time import sleep 4 | import mechanicalsoup 5 | 6 | my_browser = mechanicalsoup.Browser() 7 | 8 | # obtain 1 stock quote per minute for the next 3 minutes 9 | for i in range(0, 3): 10 | 11 | page = my_browser.get("http://finance.yahoo.com/q?s=yhoo") 12 | html_text = page.soup 13 | 14 | # return a list of all the tags where the id is 'yfs_184_yhoo' 15 | my_price_tag = html_text.select("#yfs_l84_yhoo") 16 | # take the BeautifulSoup string out of the first tag 17 | my_price = my_price_tag[0].text 18 | 19 | # Grab the timestamp 20 | my_time_tag = page.soup.select("#yfs_market_time") 21 | my_time = my_time_tag[0].text 22 | my_time = my_time[:my_time.find(" - ")] # trim string to just the time 23 | 24 | print("The price of YHOO is: {} on {}".format(my_price, my_time)) 25 | 26 | if i < 2: # wait a minute if this isn't the last request 27 | sleep(60) 28 | -------------------------------------------------------------------------------- /chp14/practice_files/pirates.csv: -------------------------------------------------------------------------------- 1 | Year,Temperature,Pirates 2 | 1820,14.25,45000 3 | 1860,14.4,35000 4 | 1880,14.55,20000 5 | 1920,14.9,15000 6 | 1940,15.25,5000 7 | 1980,15.6,400 8 | 2000,15.9,17 9 | -------------------------------------------------------------------------------- /chp14/solutions/14-1.py: -------------------------------------------------------------------------------- 1 | # 14.1 review exercises 2 | 3 | # Setup 4 | import numpy 5 | 6 | 7 | # Create a 3x3 array of the number 3 through 11 using reshape() 8 | first_matrix = numpy.arange(3, 12) 9 | first_matrix = first_matrix.reshape(3, 3) 10 | 11 | # Display the min, max and mean of all entries in the matrix 12 | print "Min is", first_matrix.min() 13 | print "Max is", first_matrix.max() 14 | print "Mean is", first_matrix.mean() 15 | 16 | # Square every entry and save in a new matrix 17 | second_matrix = first_matrix ** 2 18 | 19 | # Put first_matrix on top of second_matrix 20 | third_matrix = numpy.vstack([first_matrix, second_matrix]) 21 | 22 | # Calculate the dot product of third_matrix by first_matrix 23 | print(numpy.dot(third_matrix, first_matrix)) 24 | 25 | # Reshape third_matrix into a 3x3x2 matrix 26 | third_matrix = third_matrix.reshape(3, 3, 2) 27 | print(third_matrix) 28 | -------------------------------------------------------------------------------- /chp14/solutions/pirates.py: -------------------------------------------------------------------------------- 1 | # chapter 14 pirates.py 2 | # Graph pirates versus global warming 3 | 4 | from matplotlib import pyplot as plt 5 | import csv 6 | import os 7 | path = "C:/Real Python/refactor/chp15/practice_files" 8 | 9 | years = [] 10 | temperatures = [] 11 | pirates = [] 12 | 13 | with open(os.path.join(path, "pirates.csv"), "rb") as my_file: 14 | my_file_reader = csv.reader(my_file) 15 | my_file_reader.next() # skip header row 16 | for year, temperature, pirate_count in my_file_reader: 17 | years.append(year) 18 | temperatures.append(temperature) 19 | pirates.append(pirate_count) 20 | 21 | plt.plot(pirates, temperatures, "r-o") 22 | 23 | # label graph 24 | plt.title("Global temperature as a function of pirate population") 25 | plt.xlabel("Total pirates") 26 | plt.ylabel("Average global temperature (Celsius)") 27 | plt.axis([-300, 48000, 14, 16]) 28 | 29 | # annotate points with years 30 | for i in range(0, len(years)): 31 | plt.annotate(str(years[i]), xy=(pirates[i], temperatures[i])) 32 | 33 | # save and display graph 34 | plt.savefig(os.path.join(path, "Output/pirates.png")) 35 | plt.show() 36 | -------------------------------------------------------------------------------- /chp15/15-1.py: -------------------------------------------------------------------------------- 1 | # 15.1 review exercises 2 | 3 | # Create a button that takes on the value in an entry box 4 | 5 | 6 | from tkinter import * 7 | 8 | 9 | def button_clicked(): 10 | ''' sets the button text to the text in the entry box ''' 11 | button.config(text=entry.get()) 12 | 13 | window = Tk() 14 | # Create and add button 15 | button = Button(text=" ", command=button_clicked) 16 | button.grid(row=1, column=1) 17 | # Create and add space for user entry of text 18 | entry = Entry(width=10) 19 | entry.grid(row=1, column=2) 20 | 21 | window.mainloop() 22 | -------------------------------------------------------------------------------- /chp18/_clean_data.txt: -------------------------------------------------------------------------------- 1 | Melinda Stanley (520)526-8523 2013/06/27 Ap #397-1051 Ut, Rd. Fort Worth TX Purus Gravida Rose Wood (833)559-0524 2015/01/14 540-715 Massa. St. Minneapolis MN Quis Diam September Fulton (599)759-0669 2015/04/06 Ap #538-1934 Est Road Burlington VT Leo Consulting Ignatius Simon (134)600-3345 2015/05/10 8120 Netus Street Augusta GA Tempor Erat Neque Brady Cruz (283)940-6558 2014/02/03 126-8307 Nunc Rd. Athens GA Ac Risus Roary Mosley (668)498-6240 2014/12/08 P.O. Box 265, 6218 Viverra. St. Columbia MO Mauris Non Institute Liberty Levy (602)734-2959 2015/05/17 697-3414 Aliquet Av. Dallas TX Lectus Consulting Yuli Waters (364)703-2081 2014/03/15 518-3109 Magna, Ave Juneau AK Quisque Company Guy Norton (484)388-8334 2015/05/20 Ap #102-3787 Scelerisque Rd. Wilmington DE Dignissim Tempor Arcu Harrison Garza (392)293-2493 2013/11/29 Ap #437-9630 Vestibulum Av. Stamford CT Aliquet Wallace Graham (615)659-3227 2014/09/14 4267 Sodales St. Broken Arrow OK At Arcu Vestibulum Company Haviva Webb (202)227-4282 2015/03/04 P.O. Box 516, 7826 Semper St. Fort Collins CO Dui Ltd Jasmine Wall (789)957-4807 2013/09/22 Ap #991-8460 Aliquam Rd. Birmingham AL Maecenas Libero Barbara Rosales (510)410-6406 2014/03/31 P.O. Box 720, 7832 Orci. Road Mobile AL Fermentum Chancellor Oneal (875)552-8867 2015/03/12 394-1338 Nibh. Rd. Biloxi MS Dui Ltd Colette Pollard (989)348-5958 2014/06/07 Ap #157-9280 Proin Rd. Southaven MS Dapibus Rutrum Jasper Gordon (d{3})591-0740 2015/05/02 P.O. Box 381, 4896 Sed Avenue Akron OH Pharetra Ut Kane Munoz (542)329-7528 2014/04/06 Ap #387-5145 Eu Avenue Great Falls MT Feugiat Lorem Vladimir Fields (997)908-6102 2013/07/24 P.O. Box 609, 9056 Praesent Avenue Gresham OR Erat Zahir David (907)942-7793 2014/01/25 Ap #297-2286 Consequat St. Louisville KY Duis Cursus Consulting -------------------------------------------------------------------------------- /chp18/phone-book-fun.py: -------------------------------------------------------------------------------- 1 | import re 2 | from phone_list import data 3 | 4 | 5 | def parse_phone_book(phone_book): 6 | for line in phone_book: 7 | if re.search(r'K.*Hardy', line['name']): 8 | print("{} - {}".format(line['name'], line["phone"])) 9 | 10 | parse_phone_book(data) 11 | -------------------------------------------------------------------------------- /chp18/regex-groups.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | string = "My name is Michael Herman" 4 | 5 | # re.match(pattern, string, flags=0) 6 | m = re.match(r'(.*) name (.[s]?) .*', string) 7 | # m = re.match(r'(.*) name .[s]? (.*)', string) # what does this do? 8 | 9 | if m: 10 | print("group(0): ", m.group(0)) 11 | print("group(1): ", m.group(1)) 12 | print("group(2): ", m.group(2)) 13 | else: 14 | print("Sorry. No match!!") 15 | -------------------------------------------------------------------------------- /chp18/regex-namedgroups.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | string = "Michael Herman" 4 | 5 | # re.match(pattern, string, flags=0) 6 | m = re.match(r"(?P\w+)\W+(?P\w+)", string) 7 | 8 | if m: 9 | print("group(0) : ", m.group(0)) 10 | print("group(1) : ", m.group(1)) 11 | print("group(2) : ", m.group(2)) 12 | print("") 13 | print('group("first") : ', m.group("first")) 14 | print('group("last") : ', m.group("last")) 15 | else: 16 | print("Sorry. No match!!") 17 | -------------------------------------------------------------------------------- /chp18/regex-validation-refactor.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | validation = re.compile(r'[A-Za-z0-9.]+@[A-Za-z0-9.]+.com$') 4 | 5 | email = input("Please enter your email address: ") 6 | 7 | while not validation.search(email): 8 | print("Please enter your email address correctly!") 9 | email = input("Please enter your email address: ") 10 | 11 | print("\nYour email address is {}!".format(email)) 12 | -------------------------------------------------------------------------------- /chp18/regex-validation.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | validation = re.compile(r'[A-Za-zs.]') 4 | 5 | name = input("Please enter your name: ") 6 | 7 | while not validation.search(name): 8 | print("Please enter your name correctly!") 9 | name = input("Please enter your name: ") 10 | 11 | print("\nYour name is {}!".format(name)) 12 | -------------------------------------------------------------------------------- /chp18/regex_answers.txt: -------------------------------------------------------------------------------- 1 | 1. Blank lines - ^\s*\n 2 | 1. Spaces from the beginning of each line - ^\s+ 3 | 1. Bracketed numbers (e.g., '[1]') - \[\d+\] 4 | 1. The first column of numbers - ^\d+\s+ 5 | 1. 'Inc.', ', Inc.', 'Inc', and 'Incorporated' - (,* |,)(Incorporated|Inc\.*) 6 | 1. Space between the area code, '(XXX)', and the phone number, 'XXX-XXXX' - find - (\(\d{3}\))(\s)(\d{3}-\d{4}) then replace - $1$3 -------------------------------------------------------------------------------- /chp18/regex_review.py: -------------------------------------------------------------------------------- 1 | # Modify the variable value so that all of the `print` statements return `True`. 2 | 3 | import re 4 | 5 | zero = "Python" 6 | one = "5/25/2014" 7 | two = "A88 8AA" 8 | three = '\w\d\w\s\w\d\w' 9 | four = "$4.76" 10 | five = ["haaaappy", "birthday"] 11 | six = r'\.(doc|odt)$' 12 | seven = "My email is (email redacted)" 13 | 14 | # zero = "Ruby" 15 | # one = "5/25/14" 16 | # two = "A99 9AA" 17 | # three = r'' 18 | # four = "6.76" 19 | # five = ["happy","birthday"] 20 | # six = r'\.(doc)$' 21 | # seven = "My email is michael@mherman.org" 22 | 23 | # DO NOT CHANGE ANYTHING BELOW THIS LINE # 24 | # -------------------------------------- # 25 | 26 | print("zero: {}".format( 27 | zero == re.search(r'[P].*', "This is Real Python").group()) 28 | ) 29 | print("one: {}".format( 30 | one == re.search(r'\d{1,2}\/\d{1,2}\/\d{4}', "5/25/2014").group()) 31 | ) 32 | print("two: {}".format( 33 | two == re.match( 34 | r'[A-Z]([A-Z](\d{1,2}|\d[A-Z])|\d{1,2})\s\d[A-Z]{2}', 35 | "A88 8AA", 36 | re.VERBOSE 37 | ).group() 38 | )) 39 | print("three: {}".format(bool(re.search(three, "B4c r79").group()))) 40 | print("four: {}".format(bool(re.search(r'\$[0-5]\.\d\d', four)))) 41 | print("five: {}".format(bool(re.search(r'\ha{4,10}ppy\b', five[0])))) 42 | files = ['test.doc', 'test.odt', 'test.ddt', 'doc', 'testodt', 'test.doc'] 43 | matched_files = [file for file in files if re.search(six, file)] 44 | print("six: {}".format(len(matched_files) == 3)) 45 | email_regex = r'\w+@\w+\.(com|org|edu|net)' 46 | text = "My email is michael@mherman.org" 47 | redacted_text = re.sub(email_regex, '(email redacted)', text) 48 | print("seven: {}".format(seven == redacted_text)) 49 | -------------------------------------------------------------------------------- /chp19/dog_class.py: -------------------------------------------------------------------------------- 1 | class Dog(): 2 | 3 | # Class Attribute 4 | species = 'mammal' 5 | 6 | # Initializer / Instance Attributes 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | 12 | # Instantiate the Dog object 13 | philo = Dog("Philo", 5) 14 | mikey = Dog("Mikey", 6) 15 | 16 | # Access the instance attributes 17 | print("{} is {} and {} is {}.".format( 18 | philo.name, philo.age, mikey.name, mikey.age)) 19 | 20 | # Is Philo a mammal? 21 | if philo.species == "mammal": 22 | print("{0} is a {1}!".format(philo.name, philo.species)) 23 | -------------------------------------------------------------------------------- /chp19/dog_inheritance.py: -------------------------------------------------------------------------------- 1 | # Parent class 2 | class Dog(): 3 | 4 | # Class attribute 5 | species = 'mammal' 6 | 7 | # Initializer / Instance attributes 8 | def __init__(self, name, age): 9 | self.name = name 10 | self.age = age 11 | 12 | # instance method 13 | def description(self): 14 | return self.name, self.age 15 | 16 | # instance method 17 | def speak(self, sound): 18 | return "%s says %s" % (self.name, sound) 19 | 20 | 21 | # child class (inherits from Dog() class) 22 | class RussellTerrier(Dog): 23 | def run(self, speed): 24 | return "%s runs %s" % (self.name, speed) 25 | 26 | 27 | # child class (inherits from Dog() class) 28 | class Bulldog(Dog): 29 | def run(self, speed): 30 | return "%s runs %s" % (self.name, speed) 31 | 32 | 33 | # child classes inherit attributes and 34 | # behaviors from the parent class 35 | jim = Bulldog("Jim", 12) 36 | print(jim.description()) 37 | 38 | # child classes have specific attributes 39 | # and behaviors as well 40 | print(jim.run("slow")) 41 | -------------------------------------------------------------------------------- /chp19/dog_instance_methods.py: -------------------------------------------------------------------------------- 1 | class Dog(): 2 | 3 | # Class Attribute 4 | species = 'mammal' 5 | 6 | # Initializer / Instance Attributes 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | # instance method 12 | def description(self): 13 | return self.name, self.age 14 | 15 | # instance method 16 | def speak(self, sound): 17 | return "%s says %s" % (self.name, sound) 18 | 19 | # Instantiate the Dog object 20 | mikey = Dog("Mikey", 6) 21 | 22 | # call our instance methods 23 | print(mikey.description()) 24 | print(mikey.speak("Gruff Gruff")) 25 | -------------------------------------------------------------------------------- /chp19/dog_isinstance.py: -------------------------------------------------------------------------------- 1 | # Parent class 2 | class Dog(): 3 | 4 | # Class attribute 5 | species = 'mammal' 6 | 7 | # Initializer / Instance attributes 8 | def __init__(self, name, age): 9 | self.name = name 10 | self.age = age 11 | 12 | # instance method 13 | def description(self): 14 | return self.name, self.age 15 | 16 | # instance method 17 | def speak(self, sound): 18 | return "%s says %s" % (self.name, sound) 19 | 20 | 21 | # child class (inherits from Dog() class) 22 | class RussellTerrier(Dog): 23 | def run(self, speed): 24 | return "%s runs %s" % (self.name, speed) 25 | 26 | 27 | # child class (inherits from Dog() class) 28 | class Bulldog(Dog): 29 | def run(self, speed): 30 | return "%s runs %s" % (self.name, speed) 31 | 32 | 33 | # child classes inherit attributes and 34 | # behaviors from the parent class 35 | jim = Bulldog("Jim", 12) 36 | print(jim.description()) 37 | 38 | # child classes have specific attributes 39 | # and behaviors as well 40 | print(jim.run("slow")) 41 | 42 | # is jim an instance of Dog()? 43 | print(isinstance(jim, Dog)) 44 | 45 | # is julie an instance of Dog()? 46 | julie = Dog("Julie", 100) 47 | print(isinstance(julie, Dog)) 48 | 49 | # is johnny walker an instance of Bulldog() 50 | johnnywalker = RussellTerrier("Johnny Walker", 4) 51 | print(isinstance(johnnywalker, Bulldog)) 52 | 53 | # is julie and instance of jim? 54 | print(isinstance(julie, jim)) 55 | -------------------------------------------------------------------------------- /chp19/dog_walking.py: -------------------------------------------------------------------------------- 1 | # parent class 2 | class Pet(): 3 | 4 | dogs = [] 5 | 6 | def __init__(self, dogs): 7 | self.dogs = dogs 8 | 9 | def walk(self): 10 | for dog in self.dogs: 11 | print(dog.walk()) 12 | 13 | 14 | # parent class 15 | class Dog(): 16 | 17 | # class attribute 18 | species = 'mammal' 19 | is_hungry = True 20 | 21 | # initializer / instance attributes 22 | def __init__(self, name, age): 23 | self.name = name 24 | self.age = age 25 | 26 | # instance method 27 | def description(self): 28 | return self.name, self.age 29 | 30 | # instance method 31 | def speak(self, sound): 32 | return "%s says %s" % (self.name, sound) 33 | 34 | # instance method 35 | def eat(self): 36 | self.is_hungry = False 37 | 38 | def walk(self): 39 | return "%s is walking!" % (self.name) 40 | 41 | 42 | # child class (inherits from Dog() class) 43 | class RussellTerrier(Dog): 44 | def run(self, speed): 45 | return "%s runs %s" % (self.name, speed) 46 | 47 | 48 | # child class (inherits from Dog() class) 49 | class Bulldog(Dog): 50 | def run(self, speed): 51 | return "%s runs %s" % (self.name, speed) 52 | 53 | # create instances of dogs 54 | my_dogs = [Bulldog("Tom", 6), RussellTerrier("Fletcher", 7), Dog("Larry", 9)] 55 | 56 | # instantiate the Pet() class 57 | my_pets = Pet(my_dogs) 58 | 59 | # output 60 | my_pets.walk() 61 | -------------------------------------------------------------------------------- /chp19/github_with_class.py: -------------------------------------------------------------------------------- 1 | from urllib.request import Request, urlopen 2 | 3 | 4 | class Github(object): 5 | 6 | def __init__(self, username): 7 | self.username = username 8 | self.base_url = 'https://api.github.com/users/' 9 | 10 | def get_user_info(self): 11 | full_url = "{0}{1}".format(self.base_url, self.username) 12 | request = Request(full_url) 13 | handler = urlopen(request) 14 | if handler.getcode() == 200: 15 | return handler.read() 16 | 17 | def get_user_repos(self): 18 | full_url = "{0}{1}/repos".format(self.base_url, self.username) 19 | request = Request(full_url) 20 | handler = urlopen(request) 21 | if handler.getcode() == 200: 22 | return handler.read() 23 | 24 | 25 | user = Github('mjhea0') 26 | print(user.get_user_info()) 27 | print(user.get_user_repos()) 28 | -------------------------------------------------------------------------------- /chp19/oldest_dog.py: -------------------------------------------------------------------------------- 1 | class Dog(): 2 | 3 | # Class Attribute 4 | species = 'mammal' 5 | 6 | # Initializer / Instance Attributes 7 | def __init__(self, name, age): 8 | self.name = name 9 | self.age = age 10 | 11 | 12 | # Instantiate the Dog object 13 | jake = Dog("Jake", 7) 14 | doug = Dog("Doug", 4) 15 | william = Dog("William", 5) 16 | 17 | 18 | # Determine the oldest dog 19 | def get_biggest_number(*args): 20 | return max(args) 21 | 22 | # output 23 | print("The oldest dog is {} years old.".format( 24 | get_biggest_number(jake.age, doug.age, william.age))) 25 | -------------------------------------------------------------------------------- /chp19/pet_class.py: -------------------------------------------------------------------------------- 1 | # parent class 2 | class Pet(): 3 | 4 | dogs = [] 5 | 6 | def __init__(self, dogs): 7 | self.dogs = dogs 8 | 9 | 10 | # parent class 11 | class Dog(): 12 | 13 | # class attribute 14 | species = 'mammal' 15 | is_hungry = True 16 | 17 | # initializer / Instance attributes 18 | def __init__(self, name, age): 19 | self.name = name 20 | self.age = age 21 | 22 | # instance method 23 | def description(self): 24 | return self.name, self.age 25 | 26 | # instance method 27 | def speak(self, sound): 28 | return "%s says %s" % (self.name, sound) 29 | 30 | # instance method 31 | def eat(self): 32 | self.is_hungry = False 33 | 34 | 35 | # child class (inherits from Dog() class) 36 | class RussellTerrier(Dog): 37 | def run(self, speed): 38 | return "%s runs %s" % (self.name, speed) 39 | 40 | 41 | # child class (inherits from Dog() class) 42 | class Bulldog(Dog): 43 | def run(self, speed): 44 | return "%s runs %s" % (self.name, speed) 45 | 46 | # create instances of dogs 47 | my_dogs = [Bulldog("Tom", 6), RussellTerrier("Fletcher", 7), Dog("Larry", 9)] 48 | 49 | # instantiate the Pet() class 50 | my_pets = Pet(my_dogs) 51 | 52 | # output 53 | print("I have {} dogs.".format(len(my_pets.dogs))), 54 | for dog in my_pets.dogs: 55 | dog.eat() 56 | print("{} is {}.".format(dog.name, dog.age)), 57 | print("And they're all {}s, of course.".format(dog.species)), 58 | if dog.is_hungry is True: 59 | print("My dogs are hungry.") 60 | else: 61 | print("My dogs are not hungry.") 62 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | Course materials for Real Python Course 1: *Introduction to Python* --------------------------------------------------------------------------------