diff --git a/.gitignore b/.gitignore index db91cf5..5eda0c9 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ py3venv env *.pyc __pycache__/ -.DS_Store \ No newline at end of file +.DS_Store +.vscode \ No newline at end of file diff --git a/chp18/_clean_data.txt b/appendix-B-regular-expressions/_clean_data.txt similarity index 100% rename from chp18/_clean_data.txt rename to appendix-B-regular-expressions/_clean_data.txt diff --git a/chp18/_sloppy_data.txt b/appendix-B-regular-expressions/_sloppy_data.txt similarity index 100% rename from chp18/_sloppy_data.txt rename to appendix-B-regular-expressions/_sloppy_data.txt diff --git a/chp18/phone-book-fun.py b/appendix-B-regular-expressions/phone-book-fun.py similarity index 100% rename from chp18/phone-book-fun.py rename to appendix-B-regular-expressions/phone-book-fun.py diff --git a/chp18/phone_list.py b/appendix-B-regular-expressions/phone_list.py similarity index 100% rename from chp18/phone_list.py rename to appendix-B-regular-expressions/phone_list.py diff --git a/chp18/regex-groups.py b/appendix-B-regular-expressions/regex-groups.py similarity index 100% rename from chp18/regex-groups.py rename to appendix-B-regular-expressions/regex-groups.py diff --git a/chp18/regex-namedgroups.py b/appendix-B-regular-expressions/regex-namedgroups.py similarity index 100% rename from chp18/regex-namedgroups.py rename to appendix-B-regular-expressions/regex-namedgroups.py diff --git a/chp18/regex-validation-refactor.py b/appendix-B-regular-expressions/regex-validation-refactor.py similarity index 100% rename from chp18/regex-validation-refactor.py rename to appendix-B-regular-expressions/regex-validation-refactor.py diff --git a/chp18/regex-validation.py b/appendix-B-regular-expressions/regex-validation.py similarity index 100% rename from chp18/regex-validation.py rename to appendix-B-regular-expressions/regex-validation.py diff --git a/chp18/regex_answers.txt b/appendix-B-regular-expressions/regex_answers.txt similarity index 100% rename from chp18/regex_answers.txt rename to appendix-B-regular-expressions/regex_answers.txt diff --git a/chp18/regex_review.py b/appendix-B-regular-expressions/regex_review.py similarity index 100% rename from chp18/regex_review.py rename to appendix-B-regular-expressions/regex_review.py diff --git a/chp19/dog_class.py b/appendix-C-primer-on-oop/dog_class.py similarity index 100% rename from chp19/dog_class.py rename to appendix-C-primer-on-oop/dog_class.py diff --git a/chp19/dog_inheritance.py b/appendix-C-primer-on-oop/dog_inheritance.py similarity index 100% rename from chp19/dog_inheritance.py rename to appendix-C-primer-on-oop/dog_inheritance.py diff --git a/chp19/dog_instance_methods.py b/appendix-C-primer-on-oop/dog_instance_methods.py similarity index 100% rename from chp19/dog_instance_methods.py rename to appendix-C-primer-on-oop/dog_instance_methods.py diff --git a/chp19/dog_isinstance.py b/appendix-C-primer-on-oop/dog_isinstance.py similarity index 100% rename from chp19/dog_isinstance.py rename to appendix-C-primer-on-oop/dog_isinstance.py diff --git a/chp19/dog_walking.py b/appendix-C-primer-on-oop/dog_walking.py similarity index 100% rename from chp19/dog_walking.py rename to appendix-C-primer-on-oop/dog_walking.py diff --git a/chp19/github_with_class.py b/appendix-C-primer-on-oop/github_with_class.py similarity index 100% rename from chp19/github_with_class.py rename to appendix-C-primer-on-oop/github_with_class.py diff --git a/chp19/my_farm.py b/appendix-C-primer-on-oop/my_farm.py similarity index 100% rename from chp19/my_farm.py rename to appendix-C-primer-on-oop/my_farm.py diff --git a/chp19/oldest_dog.py b/appendix-C-primer-on-oop/oldest_dog.py similarity index 100% rename from chp19/oldest_dog.py rename to appendix-C-primer-on-oop/oldest_dog.py diff --git a/chp19/oop_comp_check.md b/appendix-C-primer-on-oop/oop_comp_check.md similarity index 100% rename from chp19/oop_comp_check.md rename to appendix-C-primer-on-oop/oop_comp_check.md diff --git a/chp19/pet_class.py b/appendix-C-primer-on-oop/pet_class.py similarity index 100% rename from chp19/pet_class.py rename to appendix-C-primer-on-oop/pet_class.py diff --git a/chp01/1-1.py b/ch02-getting-started/1-2-4.py similarity index 66% rename from chp01/1-1.py rename to ch02-getting-started/1-2-4.py index a6b8996..47519f6 100755 --- a/chp01/1-1.py +++ b/ch02-getting-started/1-2-4.py @@ -1,7 +1,9 @@ -# 1.1 review exercises +# 1.2.4 - Screw Things Up +# Solutions to review exercies -''' The following line won't run because of a syntax error ''' +# Exercise 1 +# The following line won't run because of a syntax error print("hi) # We didn't close the double quotes at the end of the string. @@ -9,6 +11,7 @@ # print("hi") +# Exercise 2 ''' The following lines won't run properly, even if the syntax error in the line above is corrected, because of a run-time error ''' @@ -17,5 +20,5 @@ # We meant to print the string "hello"; # a variable named 'hello' doesn't exist yet. # This line could have been: -# myString = "hello" -# print(myString) +# my_string = "hello" +# print(my_string) diff --git a/ch02-getting-started/1-2-5.py b/ch02-getting-started/1-2-5.py new file mode 100755 index 0000000..1cd88b5 --- /dev/null +++ b/ch02-getting-started/1-2-5.py @@ -0,0 +1,15 @@ +# 1.2.5 - Store a Variable +# Solutions to review exercies + + +# Exercise 3 (exercises 1 and 2 are done in interactive window) +# This solution works for Exercises 1 and 2 by typing the same lines into the +# interactive window. + +# display a string directly +print("hello") + + +# display the contents of a string variable +my_string = "hi" +print(my_string) diff --git a/ch04-fundamentals-strings-and-methods/1-4-0.py b/ch04-fundamentals-strings-and-methods/1-4-0.py new file mode 100755 index 0000000..2a278bd --- /dev/null +++ b/ch04-fundamentals-strings-and-methods/1-4-0.py @@ -0,0 +1,20 @@ +# 1.4 - Fundamentals: Strings and Methods +# Solutions to review exercies + + +# Exercise 1 +print('There are "double quotes" in this string.') + + +# Exercise 2 +print("This string's got an apostrophe.") + + +# Exercise 3 +print('''This string was written on multiple lines, + and it displays across multiple lines''') + + +# Exercise 4 +print("This one-line string was written out \ + using multiple lines") diff --git a/chp03/3-2.py b/ch04-fundamentals-strings-and-methods/1-4-1.py similarity index 79% rename from chp03/3-2.py rename to ch04-fundamentals-strings-and-methods/1-4-1.py index e0e1223..f1ab41a 100755 --- a/chp03/3-2.py +++ b/ch04-fundamentals-strings-and-methods/1-4-1.py @@ -1,25 +1,29 @@ -# 3.2 review exercises +# 1.4.1 - Mess Around With Your Words +# Solutions to review exercies +# Exercise 1 # Display the number of letters in the string my_word = "antidisestablishmentarianism" print(len(my_word)) +# Exercise 2 # Concatenate two strings together string_left = "bat" string_right = "man" print(string_left + string_right) +# Exercise 3 # Display two strings together, with a space in between string_one = "heebie" string_two = "jeebies" print(string_one, string_two) +# Exercise 4 # Use subscripting to display part of a string print("bazinga"[2:6]) - # A more advanced way to do the above example would be: my_string = "bazinga" start_index = 2 diff --git a/chp03/3-3.py b/ch04-fundamentals-strings-and-methods/1-4-2.py similarity index 64% rename from chp03/3-3.py rename to ch04-fundamentals-strings-and-methods/1-4-2.py index 4c876ce..a4646e7 100755 --- a/chp03/3-3.py +++ b/ch04-fundamentals-strings-and-methods/1-4-2.py @@ -1,8 +1,13 @@ -# 3.3 review exercises +# 1.4.2 - Use Objects and Methods +# Solutions to review exercies + +# Exercise 1 # Take input from the user and display that input back my_input = input("Type something: ") print(my_input) + +# Exercise 2 # Display the input string converted to lower-case letters print(my_input.lower()) diff --git a/chp03/first_letter.py b/ch04-fundamentals-strings-and-methods/1-4-3.py similarity index 69% rename from chp03/first_letter.py rename to ch04-fundamentals-strings-and-methods/1-4-3.py index 7aac7a4..32b0753 100755 --- a/chp03/first_letter.py +++ b/ch04-fundamentals-strings-and-methods/1-4-3.py @@ -1,4 +1,7 @@ -# chapter 3 first_letter.py +# 1.4.3 - Assignment: Pick Apart Your User's Input +# Solution to assignment + + # Return the upper-case first letter entered by the user user_input = input("Tell me your password: ") diff --git a/chp04/4-1.py b/ch05-fundamentals-working-with-strings/1-5-0.py similarity index 79% rename from chp04/4-1.py rename to ch05-fundamentals-working-with-strings/1-5-0.py index fde0711..04ec4d8 100755 --- a/chp04/4-1.py +++ b/ch05-fundamentals-working-with-strings/1-5-0.py @@ -1,6 +1,8 @@ -# 4.1 review exercises +# 1.5.0 - Fundamentals: Working with Strings +# Solutions to review exercies +# Exercise 1 # Store an integer as a string my_integer_string = "6" @@ -9,6 +11,7 @@ print(int(my_integer_string) * 7) +# Exercise 2 # Store a floating-point number as a string my_float_string = "6.01" @@ -17,6 +20,7 @@ print(float(my_float_string) * 7) +# Exercise 3 # Create a string and an int object, then display them together my_string = "mp" my_int = 3 diff --git a/chp04/4-2.py b/ch05-fundamentals-working-with-strings/1-5-1.py similarity index 72% rename from chp04/4-2.py rename to ch05-fundamentals-working-with-strings/1-5-1.py index 3cdc5f4..f252091 100755 --- a/chp04/4-2.py +++ b/ch05-fundamentals-working-with-strings/1-5-1.py @@ -1,20 +1,31 @@ -# 4.2 review exercises +# 1.5.1 - Streamline Your Print Statements +# Solutions to review exercies + +# Exercise 1 weight = 0.2 animal = "newt" # Concatenate a number and a string in one print statement print(str(weight) + " kg is the weight of the newt.") + +# Exercise 2 # Use format() to print a number and a string inside of another string print("{} kg is the weight of the {}.".format(weight, animal)) + +# Exercise 3 # Use format() to add objects inside a string using index numbers # (Here we reversed the arguments - just because we could.) print("{1} kg is the weight of the {0}.".format(animal, weight)) + +# Exercise 4 # Use format() to print new objects inside a string print("{} kg is the weight of the {}.".format(0.2, "newt")) -# Use formatted string literal to reference new objects inside a string + +# Exercise 5 +# Use formatted string literal to reference objects inside a string print(f"{weight} kg is the weight of the {animal}.") diff --git a/chp04/4-3.py b/ch05-fundamentals-working-with-strings/1-5-2.py similarity index 72% rename from chp04/4-3.py rename to ch05-fundamentals-working-with-strings/1-5-2.py index 58ba5d2..824df5c 100755 --- a/chp04/4-3.py +++ b/ch05-fundamentals-working-with-strings/1-5-2.py @@ -1,10 +1,13 @@ -# 4.3 review exercises +# 1.5.2 - Find a String in a String +# Solutions to review exercies +# Exercise 1 # Cannot find the string "a" in the string "AAA": print("AAA".find("a")) +# Exercise 2 # Try to find a number inside a string; # use str() to convert the number first version = "version 2.0" @@ -12,6 +15,7 @@ print(version.find(str(v_num))) +# Exercise 3 # Try to find an upper-case "X" in user input: my_input = input("Type something: ") print(my_input.find("X")) diff --git a/chp04/translate.py b/ch05-fundamentals-working-with-strings/1-5-3.py similarity index 77% rename from chp04/translate.py rename to ch05-fundamentals-working-with-strings/1-5-3.py index 551ada6..683b4de 100755 --- a/chp04/translate.py +++ b/ch05-fundamentals-working-with-strings/1-5-3.py @@ -1,4 +1,7 @@ -# chapter 4 translate.py +# 1.5.3 - Assignment: Turn Your User Into a l33t h4x0r +# Solution to assignment + + # Turn a user's input into leetspeak my_text = input("Enter some text: ") diff --git a/chp05/exponent.py b/ch06-fundamentals-functions-and-loops/1-6-1.py similarity index 71% rename from chp05/exponent.py rename to ch06-fundamentals-functions-and-loops/1-6-1.py index a07e781..8ec63b6 100755 --- a/chp05/exponent.py +++ b/ch06-fundamentals-functions-and-loops/1-6-1.py @@ -1,4 +1,7 @@ -# chapter 5 exponent.py +# 1.6.1 - Assignment: Perform Calculations on User Input +# Solution to Assignment + + # Receive two input numbers and calculate their power base = input("Enter a base: ") diff --git a/chp05/5-1.py b/ch06-fundamentals-functions-and-loops/1-6-3.py similarity index 52% rename from chp05/5-1.py rename to ch06-fundamentals-functions-and-loops/1-6-3.py index c5eece4..4881ad0 100755 --- a/chp05/5-1.py +++ b/ch06-fundamentals-functions-and-loops/1-6-3.py @@ -1,18 +1,23 @@ -# 5.1 review exercises +# 1.6.3 - Functions Summary +# Solutions to review exercises +# Exercise 1 def cube(num): - ''' Returns the cube of the input number ''' + """Return the cube of the input number.""" cube_num = num * num * num return cube_num + print("0 cubed is", cube(0)) print("2 cubed is", cube(2)) +# Exercise 2 def multiply(num1, num2): - ''' Returns the result of multiplying two input numbers ''' + """Return the result of multiplying two input numbers.""" return num1 * num2 + mult_result = multiply(2, 5) print("2 times 5 is", mult_result) diff --git a/chp05/temperature.py b/ch06-fundamentals-functions-and-loops/1-6-4.py similarity index 82% rename from chp05/temperature.py rename to ch06-fundamentals-functions-and-loops/1-6-4.py index 8456f93..6f2fc3d 100755 --- a/chp05/temperature.py +++ b/ch06-fundamentals-functions-and-loops/1-6-4.py @@ -1,6 +1,8 @@ -# chapter 5 temperature.py -# Convert Celsius and Fahrenheit temperatures using functions +# 1.6.4 - Assignment: Convert temperatures +# Solution to assignment + +# Convert Celsius and Fahrenheit temperatures using functions def convert_cel_to_far(cel_temp): far_temp = cel_temp * 9 / 5 + 32 @@ -11,6 +13,7 @@ def convert_far_to_cel(far_temp): cel_temp = (far_temp - 32) * 5 / 9 return cel_temp + temp1 = 72 print("{} degrees F = {} degrees C".format(temp1, convert_far_to_cel(temp1))) diff --git a/chp05/5-2.py b/ch06-fundamentals-functions-and-loops/1-6-5.py similarity index 65% rename from chp05/5-2.py rename to ch06-fundamentals-functions-and-loops/1-6-5.py index 362b821..f6fd804 100755 --- a/chp05/5-2.py +++ b/ch06-fundamentals-functions-and-loops/1-6-5.py @@ -1,11 +1,14 @@ -# 5.2 review exercises +# 1.6.5 - Run in Circles +# Solutions to review exercises +# Exercise 1 # print the integer 2 through 10 using a "for" loop for i in range(2, 11): print(i) +# Exercise 2 # print the integer 2 through 10 using a "while" loop i = 2 while (i < 11): @@ -13,10 +16,12 @@ i = i + 1 +# Exercise 3 def doubles(num): - ''' Return the result of multiplying an input number by 2 ''' + """Return the result of multiplying an input number by 2.""" return num * 2 + # Call doubles to double the number 2 three times my_num = 2 for i in range(0, 3): diff --git a/chp05/invest.py b/ch06-fundamentals-functions-and-loops/1-6-6.py similarity index 80% rename from chp05/invest.py rename to ch06-fundamentals-functions-and-loops/1-6-6.py index c4e839c..5b55fc9 100755 --- a/chp05/invest.py +++ b/ch06-fundamentals-functions-and-loops/1-6-6.py @@ -1,6 +1,8 @@ -# chapter 5 invest.py -# calculate compound interest to track the growth of an investment +# 1.6.6 - Assignment: Track Your Investments +# Solution to Assignment + +# calculate compound interest to track the growth of an investment def invest(amount, rate, time): print("principal amount: ${}".format(amount)) @@ -10,5 +12,6 @@ def invest(amount, rate, time): print("year {}: ${}".format(t, amount)) print() + invest(100, .05, 8) invest(2000, .025, 5) diff --git a/chp07/7-1.py b/ch08-fundamentals-conditional-logic/1-8-1.py similarity index 69% rename from chp07/7-1.py rename to ch08-fundamentals-conditional-logic/1-8-1.py index 3aa885d..ae11077 100755 --- a/chp07/7-1.py +++ b/ch08-fundamentals-conditional-logic/1-8-1.py @@ -1,7 +1,9 @@ -# 7.1 review exercises +# 1.8.1 - Compare Values +# Solutions to review exercises # Test whether these expressions are True or False + print(1 <= 1) print(1 != 1) print(1 != 2) diff --git a/chp07/7-2.py b/ch08-fundamentals-conditional-logic/1-8-2.py similarity index 72% rename from chp07/7-2.py rename to ch08-fundamentals-conditional-logic/1-8-2.py index 1738835..a2e52dc 100755 --- a/chp07/7-2.py +++ b/ch08-fundamentals-conditional-logic/1-8-2.py @@ -1,7 +1,9 @@ -# 7.2 review exercises +# 1.8.2 - Add Some Logic +# Solutions to review exercises # Test whether these expressions are True or False + print((1 <= 1) and (1 != 1)) print(not (1 != 2)) print(("good" != "bad") or False) diff --git a/chp07/7-3.py b/ch08-fundamentals-conditional-logic/1-8-3.py similarity index 78% rename from chp07/7-3.py rename to ch08-fundamentals-conditional-logic/1-8-3.py index 33aa807..3b2692e 100755 --- a/chp07/7-3.py +++ b/ch08-fundamentals-conditional-logic/1-8-3.py @@ -1,7 +1,9 @@ -# 7.3 review exercises +# 1.8.3 - Control the Flow of Your Program +# Solutions to review exercises # Display whether the length of user input is <, > or = 5 characters + my_input = input("Type something: ") if len(my_input) < 5: diff --git a/chp07/factors.py b/ch08-fundamentals-conditional-logic/1-8-4.py similarity index 71% rename from chp07/factors.py rename to ch08-fundamentals-conditional-logic/1-8-4.py index c79c75c..ac15569 100755 --- a/chp07/factors.py +++ b/ch08-fundamentals-conditional-logic/1-8-4.py @@ -1,4 +1,7 @@ -# chapter 7 factors.py +# 1.8.4 - Assignment: Find the Factors of a Number +# Solution to assignment + + # display all the factors of a number chosen by the user num = int(input("Enter a positive integer: ")) diff --git a/chp07/7-4.py b/ch08-fundamentals-conditional-logic/1-8-5.py similarity index 73% rename from chp07/7-4.py rename to ch08-fundamentals-conditional-logic/1-8-5.py index eef74dc..9af9a91 100755 --- a/chp07/7-4.py +++ b/ch08-fundamentals-conditional-logic/1-8-5.py @@ -1,12 +1,16 @@ -# 7.4 review exercises +# 1.8.5 - Break Out of the Pattern +# Solutions to review exercises +# Exercise 1 # Run in an infinite loop until the user types "q" or "Q" while True: my_input = input('Type "q" or "Q" to quit: ') if my_input.upper() == "Q": break + +# Exercise 2 # Display every number from 1 through 50 except multiples of 3 for i in range(1, 51): if i % 3 == 0: diff --git a/chp07/7-5.py b/ch08-fundamentals-conditional-logic/1-8-6.py similarity index 79% rename from chp07/7-5.py rename to ch08-fundamentals-conditional-logic/1-8-6.py index a675f89..7efd00a 100755 --- a/chp07/7-5.py +++ b/ch08-fundamentals-conditional-logic/1-8-6.py @@ -1,4 +1,5 @@ -# 7.5 review exercises +# 1.8.6 - Recover From Errors +# Solution to review exercises # Ask the user to enter an integer. diff --git a/chp07/7-6.py b/ch08-fundamentals-conditional-logic/1-8-7.py similarity index 71% rename from chp07/7-6.py rename to ch08-fundamentals-conditional-logic/1-8-7.py index d527e5d..721f75c 100755 --- a/chp07/7-6.py +++ b/ch08-fundamentals-conditional-logic/1-8-7.py @@ -1,12 +1,16 @@ -# 7.6 review exercises +# 1.8.7 - Simulate Events and Calculate Probabilities +# Solutions to review exercises + from random import randint +# Exercise 1 # Simulate the toss of a die print(randint(1, 6)) +# Exercise 2 # Simulate 10,000 throws of dice and display the average result trials = 10000 total = 0 diff --git a/chp07/election.py b/ch08-fundamentals-conditional-logic/1-8-8.py similarity index 86% rename from chp07/election.py rename to ch08-fundamentals-conditional-logic/1-8-8.py index c8f87e7..ac4eeb3 100755 --- a/chp07/election.py +++ b/ch08-fundamentals-conditional-logic/1-8-8.py @@ -1,4 +1,7 @@ -# chapter 7 election.py +# 1.8.8 - Assignment: Simulate an Election +# Solution to assignment + + # Simulate the results of an election using a Monte Carlo simulation from random import random diff --git a/chp07/coin_toss.py b/ch08-fundamentals-conditional-logic/1-8-9a.py similarity index 86% rename from chp07/coin_toss.py rename to ch08-fundamentals-conditional-logic/1-8-9a.py index 625249a..a85e27f 100755 --- a/chp07/coin_toss.py +++ b/ch08-fundamentals-conditional-logic/1-8-9a.py @@ -1,4 +1,7 @@ -# chapter 7 coin_toss.py +# 1.8.9 - Simulate a Coin Toss Experiment +# Solution to assignment + + # Simulate the results of a series of coin tosses and track the results from random import randint diff --git a/chp07/coin_toss_alternative.py b/ch08-fundamentals-conditional-logic/1-8-9b.py similarity index 75% rename from chp07/coin_toss_alternative.py rename to ch08-fundamentals-conditional-logic/1-8-9b.py index af1ded6..108cb29 100755 --- a/chp07/coin_toss_alternative.py +++ b/ch08-fundamentals-conditional-logic/1-8-9b.py @@ -1,4 +1,7 @@ -# chapter 7 coin_toss_alternative.py +# 1.8.9 - Assignment: Simulate a Coin Toss Experiement +# Alternative solution to assignment + + # Simulate the results of a series of coin tosses and track the results from random import randint diff --git a/chp07/coin_toss_functions.py b/ch08-fundamentals-conditional-logic/1-8-9c.py similarity index 71% rename from chp07/coin_toss_functions.py rename to ch08-fundamentals-conditional-logic/1-8-9c.py index 9266815..f7f2349 100644 --- a/chp07/coin_toss_functions.py +++ b/ch08-fundamentals-conditional-logic/1-8-9c.py @@ -1,3 +1,9 @@ +# 1.8.9 - Assignment: Simulate a Coin Toss Experiement +# Alternative solution to assignment using functions + + +# Simulate the results of a series of coin tosses and track the results + from random import randint @@ -19,4 +25,5 @@ def flip_trial_avg(num_trials): total += single_trial() return total / num_trials + print("The average number of coin flips was {0}".format(flip_trial_avg(10000))) diff --git a/chp08/8-1.py b/ch09-fundamentals-lists-and-dictionaries/1-9-0.py similarity index 61% rename from chp08/8-1.py rename to ch09-fundamentals-lists-and-dictionaries/1-9-0.py index e5a9507..3a232ec 100755 --- a/chp08/8-1.py +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-0.py @@ -1,50 +1,65 @@ -# 8.1 review exercises +# 1.9.0 - Fundamentals: Lists and Dictionaries +# Solutions to review exercises +# Exercise 1 desserts = ["ice cream", "cookies"] -# Sort the desserts list alphabetically -desserts.sort() -# Display the sorted list +# Exercise 2 +# Sort the desserts list alphabetically and display the sorted list +desserts.sort() print(desserts) + +# Exercise 3 # Display the index value of "ice cream" print(desserts.index("ice cream")) + +# Exercise 4 # Copy the contents of the "desserts" list into a new "food" list food = desserts[:] + +# Exercise 5 # Add some food to the list food.append("broccoli") food.append("turnips") + +# Exercise 6 # Display the contents of both lists print(desserts) print(food) + +# Exercise 7 # Take "cookies" out of the "food" list food.remove("cookies") + +# Exercise 8 # Display the first two items in the "food" list print(food[0:2]) + +# Exercise 9 # Create a "breakfast" list full of cookies and display it my_breakfast = "cookies, cookies, cookies" breakfast = my_breakfast.split(", ") print(breakfast) -""" -Define a function that takes a list of numbers, `[2, 4, 8, 16, 32, 64]`, as the -argument and then outputs only the numbers from the list that fall between 1 -and 20 (inclusive) -""" - +# Exercise 10 +# Define a function that takes a list of numbers, `[2, 4, 8, 16, 32, 64]`, as +# the argument and then outputs only the numbers from the list that fall +# between 1 and 20 (inclusive) def print_list(list_of_nums): for num in list_of_nums: if num >= 2 and num <= 20: print(num) + list_of_numbers = [2, 4, 8, 16, 32, 64] print_list(list_of_numbers) diff --git a/ch09-fundamentals-lists-and-dictionaries/1-9-1.py b/ch09-fundamentals-lists-and-dictionaries/1-9-1.py new file mode 100644 index 0000000..9f0bdae --- /dev/null +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-1.py @@ -0,0 +1,60 @@ +# 1.9.1 - Assignment: List of Lists +# Solution to assignment + + +def enrollment_stats(list_of_universities): + + # variables + total_students = [] + total_tuition = [] + + # iterate through lists, adding values + for university in list_of_universities: + total_students.append(university[1]) + total_tuition.append(university[2]) + + # return variables + return total_students, total_tuition + + +def mean(my_list): + if len(my_list) == 0: + return 'The list is empty' + list_sum = 0 + for i in range(len(my_list)): + list_sum += float(my_list[i]) + return int(list_sum / len(my_list)) + + +def median(my_list): + sorts = sorted(my_list) + length = len(sorts) + if not length % 2: + return (sorts[int(length / 2)] + sorts[int(length / 2 - 1)]) / 2.0 + return sorts[int(length / 2)] + + +universities = [ + ['California Institute of Technology', 2175, 37704], + ['Harvard', 19627, 39849], + ['Massachusetts Institute of Technology', 10566, 40732], + ['Princeton', 7802, 37000], + ['Rice', 5879, 35551], + ['Stanford', 19535, 40569], + ['Yale', 11701, 40500], +] + +totals = enrollment_stats(universities) + +print(totals[0]) + +print("\n") +print("*****" * 5) +print("Total students: {}".format(sum(totals[0]))) +print("Total tuition: $ {}".format(sum(totals[1]))) +print("\nStudent mean: {}".format(mean(totals[0]))) +print("Student median: {}".format(median(totals[0]))) +print("\nTuition mean: $ {}".format(mean(totals[1]))) +print("Tuition median: $ {}".format(median(totals[1]))) +print("*****" * 5) +print("\n") diff --git a/chp08/poetry.py b/ch09-fundamentals-lists-and-dictionaries/1-9-2.py similarity index 90% rename from chp08/poetry.py rename to ch09-fundamentals-lists-and-dictionaries/1-9-2.py index 46eab4b..7bcb9af 100755 --- a/chp08/poetry.py +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-2.py @@ -1,4 +1,7 @@ -# chapter 8 poetry.py +# 1.9.2 - Assignment: Wax Poetic +# Solution to assignment + + # Generate a random poem based on a set structure from random import choice @@ -16,7 +19,7 @@ def make_poem(): - ''' create a randomly generated poem, returned as a multi-line string''' + """Create a randomly generated poem, returned as a multi-line string.""" # Pull three nouns randomly n1 = choice(noun) n2 = choice(noun) @@ -69,4 +72,5 @@ def make_poem(): return poem + print(make_poem()) diff --git a/chp08/8-2.py b/ch09-fundamentals-lists-and-dictionaries/1-9-3.py similarity index 71% rename from chp08/8-2.py rename to ch09-fundamentals-lists-and-dictionaries/1-9-3.py index fa0f1e8..8b4c50b 100755 --- a/chp08/8-2.py +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-3.py @@ -1,13 +1,18 @@ -# 8.2 review exercises +# 1.9.3 - Make Permanent Lists +# Solutions to review exercises +# Exercise 1 # Create a tuple "cardinal_nums" with "first", "second" and "third" cardinal_nums = ("first", "second", "third") + +# Exercise 2 # Display the second object in the tuple print(cardinal_nums[1]) +# Exercise 3 # unpack the tuple into three string and display them pos1, pos2, pos3 = cardinal_nums print(pos1) diff --git a/chp08/8-3.py b/ch09-fundamentals-lists-and-dictionaries/1-9-4.py similarity index 77% rename from chp08/8-3.py rename to ch09-fundamentals-lists-and-dictionaries/1-9-4.py index a81a105..75d4122 100755 --- a/chp08/8-3.py +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-4.py @@ -1,14 +1,20 @@ -# 8.3 review exercises +# 1.9.4 - Store Relationships in Dictionaries +# Solutions to review exercises +# Exercise 1 # Create an empty dictionary birthdays = {} + +# Exercise 2 # Add some key-value pairs to the dictionary birthdays["Luke Skywalker"] = "5/25/19" birthdays["Obi-Wan Kenobi"] = "3/11/57" birthdays["Darth Vader"] = "4/1/41" + +# Exercise 3 # Check if "Yoda" and "Darth Vader exist; if not, add them if "Yoda" not in birthdays: birthdays["Yoda"] = "unknown" @@ -20,16 +26,21 @@ # if not name in birthdays: # birthdays[name] = "unknown" + +# Exercise 4 # Display the contents of the dictionary, one pair at a time for name in birthdays: print(name, birthdays[name]) + +# Exercise 5 # Remove "Darth Vader" del(birthdays["Darth Vader"]) print(birthdays) -# Bonus: could have created dictionary by passing a list to dict() +# Exercise 6 (Bonus) +# Create dictionary by passing a list to dict() birthdays = dict([("Luke Skywalker", "5/25/19"), ("Obi-Wan Kenobi", "3/11/57"), ("Darth Vader", "4/1/41")]) diff --git a/chp08/capital_city_loop.py b/ch09-fundamentals-lists-and-dictionaries/1-9-5.py similarity index 88% rename from chp08/capital_city_loop.py rename to ch09-fundamentals-lists-and-dictionaries/1-9-5.py index bb4ec6d..9bbfa9d 100644 --- a/chp08/capital_city_loop.py +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-5.py @@ -1,3 +1,7 @@ +# 1.9.5 - Assignment: Capital City Loop +# Solution to assignment + + from capitals import capitals_dict import random diff --git a/chp08/cats_with_hats.py b/ch09-fundamentals-lists-and-dictionaries/1-9-6a.py similarity index 89% rename from chp08/cats_with_hats.py rename to ch09-fundamentals-lists-and-dictionaries/1-9-6a.py index 7cbd2ea..750d6d5 100644 --- a/chp08/cats_with_hats.py +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-6a.py @@ -1,3 +1,7 @@ +# 1.9.6 - Assignment: Cats With Hats +# Solution to assignment + + def get_cats_with_hats(array_of_cats): cats_with_hats_on = [] for num in range(1, 100 + 1): @@ -12,5 +16,6 @@ def get_cats_with_hats(array_of_cats): cats_with_hats_on.append(cat) return cats_with_hats_on + cats = [False] * (100 + 1) print(get_cats_with_hats(cats)) diff --git a/chp08/cats_with_hats_alternative.py b/ch09-fundamentals-lists-and-dictionaries/1-9-6b.py similarity index 85% rename from chp08/cats_with_hats_alternative.py rename to ch09-fundamentals-lists-and-dictionaries/1-9-6b.py index bd19e2b..0d44531 100644 --- a/chp08/cats_with_hats_alternative.py +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-6b.py @@ -1,3 +1,7 @@ +# 1.9.6 - Assignment: Cats With Hats +# Alternative solution to assignment + + number_of_cats = 100 cats_with_hats = [] number_of_laps = 100 diff --git a/chp08/cats_with_hats_dict.py b/ch09-fundamentals-lists-and-dictionaries/1-9-6c.py similarity index 82% rename from chp08/cats_with_hats_dict.py rename to ch09-fundamentals-lists-and-dictionaries/1-9-6c.py index 496a0e2..a0b86b4 100644 --- a/chp08/cats_with_hats_dict.py +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-6c.py @@ -1,3 +1,7 @@ +# 1.9.6 - Assignment: Cats With Hats +# Alternative solution to assignment using dictionaries + + theCats = {} for i in range(1, 101): diff --git a/chp08/fundamental_review.py b/ch09-fundamentals-lists-and-dictionaries/1-9-7.py similarity index 93% rename from chp08/fundamental_review.py rename to ch09-fundamentals-lists-and-dictionaries/1-9-7.py index 86f0c25..79ab965 100644 --- a/chp08/fundamental_review.py +++ b/ch09-fundamentals-lists-and-dictionaries/1-9-7.py @@ -1,6 +1,6 @@ -# chapter 8 fundamental_review.py -# Reviewing the Fundamentals: -# functions, loops, lists, dicts, and conditional logic +# 1.9.7 - Assignment: Reviewing the Fundamentals +# Solution to assignment + print("\n# -- part 1 -- #") diff --git a/chp08/capitals.py b/ch09-fundamentals-lists-and-dictionaries/capitals.py similarity index 96% rename from chp08/capitals.py rename to ch09-fundamentals-lists-and-dictionaries/capitals.py index 03c0b6b..01ff2f1 100644 --- a/chp08/capitals.py +++ b/ch09-fundamentals-lists-and-dictionaries/capitals.py @@ -1,3 +1,7 @@ +# 1.9.5 - Assignment: Capital City Loop +# capitals.py + + capitals_dict = { 'Alabama': 'Montgomery', 'Alaska': 'Juneau', diff --git a/chp09/practice_files/backup/images/additional files/one last image.png b/ch10-file-input-and-output/practice_files/backup/images/additional files/one last image.png similarity index 100% rename from chp09/practice_files/backup/images/additional files/one last image.png rename to ch10-file-input-and-output/practice_files/backup/images/additional files/one last image.png diff --git a/chp09/practice_files/backup/images/an image file.gif b/ch10-file-input-and-output/practice_files/backup/images/an image file.gif similarity index 100% rename from chp09/practice_files/backup/images/an image file.gif rename to ch10-file-input-and-output/practice_files/backup/images/an image file.gif diff --git a/chp09/practice_files/backup/images/another image.gif b/ch10-file-input-and-output/practice_files/backup/images/another image.gif similarity index 100% rename from chp09/practice_files/backup/images/another image.gif rename to ch10-file-input-and-output/practice_files/backup/images/another image.gif diff --git a/chp09/practice_files/backup/images/one more image.gif b/ch10-file-input-and-output/practice_files/backup/images/one more image.gif similarity index 100% rename from chp09/practice_files/backup/images/one more image.gif rename to ch10-file-input-and-output/practice_files/backup/images/one more image.gif diff --git a/chp09/practice_files/backup/images/png file - not a gif.png b/ch10-file-input-and-output/practice_files/backup/images/png file - not a gif.png similarity index 100% rename from chp09/practice_files/backup/images/png file - not a gif.png rename to ch10-file-input-and-output/practice_files/backup/images/png file - not a gif.png diff --git a/chp09/practice_files/backup/little pics/better not delete me.txt b/ch10-file-input-and-output/practice_files/backup/little pics/better not delete me.txt similarity index 100% rename from chp09/practice_files/backup/little pics/better not delete me.txt rename to ch10-file-input-and-output/practice_files/backup/little pics/better not delete me.txt diff --git a/chp09/practice_files/backup/little pics/look in here too/definitely has to go.jpg b/ch10-file-input-and-output/practice_files/backup/little pics/look in here too/definitely has to go.jpg similarity index 100% rename from chp09/practice_files/backup/little pics/look in here too/definitely has to go.jpg rename to ch10-file-input-and-output/practice_files/backup/little pics/look in here too/definitely has to go.jpg diff --git a/chp09/practice_files/backup/little pics/save me please.jpg b/ch10-file-input-and-output/practice_files/backup/little pics/save me please.jpg similarity index 100% rename from chp09/practice_files/backup/little pics/save me please.jpg rename to ch10-file-input-and-output/practice_files/backup/little pics/save me please.jpg diff --git a/chp09/practice_files/backup/little pics/to be deleted.jpg b/ch10-file-input-and-output/practice_files/backup/little pics/to be deleted.jpg similarity index 100% rename from chp09/practice_files/backup/little pics/to be deleted.jpg rename to ch10-file-input-and-output/practice_files/backup/little pics/to be deleted.jpg diff --git a/chp09/practice_files/example.txt b/ch10-file-input-and-output/practice_files/example.txt similarity index 100% rename from chp09/practice_files/example.txt rename to ch10-file-input-and-output/practice_files/example.txt diff --git a/chp09/practice_files/images/additional files/one last image.png b/ch10-file-input-and-output/practice_files/images/additional files/one last image.png similarity index 100% rename from chp09/practice_files/images/additional files/one last image.png rename to ch10-file-input-and-output/practice_files/images/additional files/one last image.png diff --git a/chp09/practice_files/images/an image file.gif b/ch10-file-input-and-output/practice_files/images/an image file.gif similarity index 100% rename from chp09/practice_files/images/an image file.gif rename to ch10-file-input-and-output/practice_files/images/an image file.gif diff --git a/chp09/practice_files/images/another image.gif b/ch10-file-input-and-output/practice_files/images/another image.gif similarity index 100% rename from chp09/practice_files/images/another image.gif rename to ch10-file-input-and-output/practice_files/images/another image.gif diff --git a/chp09/practice_files/images/one more image.gif b/ch10-file-input-and-output/practice_files/images/one more image.gif similarity index 100% rename from chp09/practice_files/images/one more image.gif rename to ch10-file-input-and-output/practice_files/images/one more image.gif diff --git a/chp09/practice_files/images/png file - not a gif.png b/ch10-file-input-and-output/practice_files/images/png file - not a gif.png similarity index 100% rename from chp09/practice_files/images/png file - not a gif.png rename to ch10-file-input-and-output/practice_files/images/png file - not a gif.png diff --git a/chp09/practice_files/little pics/better not delete me.txt b/ch10-file-input-and-output/practice_files/little pics/better not delete me.txt similarity index 100% rename from chp09/practice_files/little pics/better not delete me.txt rename to ch10-file-input-and-output/practice_files/little pics/better not delete me.txt diff --git a/chp09/practice_files/little pics/look in here too/definitely has to go.jpg b/ch10-file-input-and-output/practice_files/little pics/look in here too/definitely has to go.jpg similarity index 100% rename from chp09/practice_files/little pics/look in here too/definitely has to go.jpg rename to ch10-file-input-and-output/practice_files/little pics/look in here too/definitely has to go.jpg diff --git a/chp09/practice_files/little pics/save me please.jpg b/ch10-file-input-and-output/practice_files/little pics/save me please.jpg similarity index 100% rename from chp09/practice_files/little pics/save me please.jpg rename to ch10-file-input-and-output/practice_files/little pics/save me please.jpg diff --git a/chp09/practice_files/little pics/to be deleted.jpg b/ch10-file-input-and-output/practice_files/little pics/to be deleted.jpg similarity index 100% rename from chp09/practice_files/little pics/to be deleted.jpg rename to ch10-file-input-and-output/practice_files/little pics/to be deleted.jpg diff --git a/chp09/practice_files/pastimes.csv b/ch10-file-input-and-output/practice_files/pastimes.csv similarity index 100% rename from chp09/practice_files/pastimes.csv rename to ch10-file-input-and-output/practice_files/pastimes.csv diff --git a/chp09/practice_files/poem.txt b/ch10-file-input-and-output/practice_files/poem.txt similarity index 100% rename from chp09/practice_files/poem.txt rename to ch10-file-input-and-output/practice_files/poem.txt diff --git a/chp09/practice_files/scores.csv b/ch10-file-input-and-output/practice_files/scores.csv similarity index 100% rename from chp09/practice_files/scores.csv rename to ch10-file-input-and-output/practice_files/scores.csv diff --git a/chp09/practice_files/tabbed wonka.csv b/ch10-file-input-and-output/practice_files/tabbed wonka.csv similarity index 100% rename from chp09/practice_files/tabbed wonka.csv rename to ch10-file-input-and-output/practice_files/tabbed wonka.csv diff --git a/chp09/practice_files/wonka.csv b/ch10-file-input-and-output/practice_files/wonka.csv similarity index 100% rename from chp09/practice_files/wonka.csv rename to ch10-file-input-and-output/practice_files/wonka.csv diff --git a/chp09/solutions/9-1.py b/ch10-file-input-and-output/solutions/1-10-0.py similarity index 92% rename from chp09/solutions/9-1.py rename to ch10-file-input-and-output/solutions/1-10-0.py index f578fd8..163b772 100755 --- a/chp09/solutions/9-1.py +++ b/ch10-file-input-and-output/solutions/1-10-0.py @@ -1,4 +1,5 @@ -# 9.1 review exercises +# 1.10 - File Input and output +# Solutions to review exercises ''' diff --git a/chp09/solutions/9-2.py b/ch10-file-input-and-output/solutions/1-10-1.py similarity index 91% rename from chp09/solutions/9-2.py rename to ch10-file-input-and-output/solutions/1-10-1.py index b074592..fb50a54 100755 --- a/chp09/solutions/9-2.py +++ b/ch10-file-input-and-output/solutions/1-10-1.py @@ -1,4 +1,5 @@ -# 9.2 review exercises +# 1.10.1 - Use More Complicated Folder Structures +# Solutions to review exercises # Initial setup diff --git a/chp09/solutions/remove_files.py b/ch10-file-input-and-output/solutions/1-10-2.py similarity index 85% rename from chp09/solutions/remove_files.py rename to ch10-file-input-and-output/solutions/1-10-2.py index ca7e658..c76e567 100755 --- a/chp09/solutions/remove_files.py +++ b/ch10-file-input-and-output/solutions/1-10-2.py @@ -1,4 +1,7 @@ -# chapter 9 remove_files.py +# 1-10-2 Assignment: Use Pattern Matching to Delete Files +# Solution to Assignment + + # Remove JPG files from multiple folders based on file size import os diff --git a/chp09/solutions/9-3.py b/ch10-file-input-and-output/solutions/1-10-3.py similarity index 91% rename from chp09/solutions/9-3.py rename to ch10-file-input-and-output/solutions/1-10-3.py index 28716ae..f18a4e2 100755 --- a/chp09/solutions/9-3.py +++ b/ch10-file-input-and-output/solutions/1-10-3.py @@ -1,4 +1,5 @@ -# 9.3 review exercises +# 1.10.2 - Read and Write CSV Data +# Solutions to review exercises # Initial setup diff --git a/chp09/solutions/high_scores.py b/ch10-file-input-and-output/solutions/1-10-4.py similarity index 82% rename from chp09/solutions/high_scores.py rename to ch10-file-input-and-output/solutions/1-10-4.py index 7689ac5..ec63696 100755 --- a/chp09/solutions/high_scores.py +++ b/ch10-file-input-and-output/solutions/1-10-4.py @@ -1,8 +1,13 @@ -# chapter 9 high_scores.py +# 1.10.4 - Assignment: Create a High Scores List From CSV Data +# Solution to assignment + + # Read in CSV data containing names and scores; display a high score list import csv import os + +# Change my_path to the correct path on your system my_path = "C:/Real Python/refactor/chp10/practice_files" high_scores_dict = {} diff --git a/chp09/solutions/csv_split.py b/ch10-file-input-and-output/solutions/1-10-5.py similarity index 96% rename from chp09/solutions/csv_split.py rename to ch10-file-input-and-output/solutions/1-10-5.py index 33bdefb..f44b638 100644 --- a/chp09/solutions/csv_split.py +++ b/ch10-file-input-and-output/solutions/1-10-5.py @@ -1,3 +1,6 @@ +# 1.10.5 - Assignment: Split a CSV File +# Solution to assignment + import sys import os import csv @@ -126,6 +129,5 @@ def parse_file(arguments): current_chunk += 1 -if __name__ == "__main__": - arguments = get_arguments() - parse_file(arguments) +arguments = get_arguments() +parse_file(arguments) diff --git a/chp09/solutions/sample_csv.csv b/ch10-file-input-and-output/solutions/sample_csv.csv similarity index 100% rename from chp09/solutions/sample_csv.csv rename to ch10-file-input-and-output/solutions/sample_csv.csv diff --git a/chp11/practice_files/Emperor cover sheet.pdf b/ch12-interact-with-pdf-files/practice_files/Emperor cover sheet.pdf similarity index 100% rename from chp11/practice_files/Emperor cover sheet.pdf rename to ch12-interact-with-pdf-files/practice_files/Emperor cover sheet.pdf diff --git a/chp11/practice_files/Pride and Prejudice.pdf b/ch12-interact-with-pdf-files/practice_files/Pride and Prejudice.pdf similarity index 100% rename from chp11/practice_files/Pride and Prejudice.pdf rename to ch12-interact-with-pdf-files/practice_files/Pride and Prejudice.pdf diff --git a/chp11/practice_files/The Emperor.pdf b/ch12-interact-with-pdf-files/practice_files/The Emperor.pdf similarity index 100% rename from chp11/practice_files/The Emperor.pdf rename to ch12-interact-with-pdf-files/practice_files/The Emperor.pdf diff --git a/chp11/practice_files/The Whistling Gypsy.pdf b/ch12-interact-with-pdf-files/practice_files/The Whistling Gypsy.pdf similarity index 100% rename from chp11/practice_files/The Whistling Gypsy.pdf rename to ch12-interact-with-pdf-files/practice_files/The Whistling Gypsy.pdf diff --git a/chp11/practice_files/Walrus.pdf b/ch12-interact-with-pdf-files/practice_files/Walrus.pdf similarity index 100% rename from chp11/practice_files/Walrus.pdf rename to ch12-interact-with-pdf-files/practice_files/Walrus.pdf diff --git a/chp11/practice_files/half and half.pdf b/ch12-interact-with-pdf-files/practice_files/half and half.pdf similarity index 100% rename from chp11/practice_files/half and half.pdf rename to ch12-interact-with-pdf-files/practice_files/half and half.pdf diff --git a/chp11/practice_files/top secret.pdf b/ch12-interact-with-pdf-files/practice_files/top secret.pdf similarity index 100% rename from chp11/practice_files/top secret.pdf rename to ch12-interact-with-pdf-files/practice_files/top secret.pdf diff --git a/chp11/practice_files/ugly.pdf b/ch12-interact-with-pdf-files/practice_files/ugly.pdf similarity index 100% rename from chp11/practice_files/ugly.pdf rename to ch12-interact-with-pdf-files/practice_files/ugly.pdf diff --git a/chp11/solutions/11-1.py b/ch12-interact-with-pdf-files/solutions/1-12-0.py similarity index 88% rename from chp11/solutions/11-1.py rename to ch12-interact-with-pdf-files/solutions/1-12-0.py index ac7fe30..3fec613 100755 --- a/chp11/solutions/11-1.py +++ b/ch12-interact-with-pdf-files/solutions/1-12-0.py @@ -1,9 +1,12 @@ -# 11.1 review exercises +# 1.12 - Interact with PDF Files +# Solutions to review exercises import os from pyPdf import PdfFileReader, PdfFileWriter + +# Exercise 1 path = "C:/Real Python/refactor/chp12/practice_files" input_file_name = os.path.join(path, "The Whistling Gypsy.pdf") input_file = PdfFileReader(open(input_file_name, "rb")) @@ -13,6 +16,8 @@ print("Author:", input_file.getDocumentInfo().author) print("Number of pages:", input_file.getNumPages()) + +# Exercise 2 # Specify and open output text file output_file_name = os.path.join(path, "Output/The Whistling Gypsy.txt") with open(output_file_name, "w") as output_file: @@ -22,6 +27,8 @@ text = text.encode("utf-8") # convert text to unicode output_file.write(text) + +# Exercise 3 # Save file without cover page output_PDF = PdfFileWriter() for page_num in range(1, input_file.getNumPages()): diff --git a/chp11/solutions/11-2.py b/ch12-interact-with-pdf-files/solutions/1-12-1.py similarity index 88% rename from chp11/solutions/11-2.py rename to ch12-interact-with-pdf-files/solutions/1-12-1.py index ee349d8..8dfc205 100755 --- a/chp11/solutions/11-2.py +++ b/ch12-interact-with-pdf-files/solutions/1-12-1.py @@ -1,9 +1,12 @@ -# 11.2 review exercises +# 1.12.1 - Manipulate PDF Files +# Solutions to review exercises import os import copy from pyPdf import PdfFileReader, PdfFileWriter + +# Exercise 1 path = "C:/Real Python/refactor/chp12/practice_files" input_file_name = os.path.join(path, "Walrus.pdf") input_file = PdfFileReader(open(input_file_name, "rb")) @@ -11,6 +14,8 @@ input_file.decrypt("IamtheWalrus") # decrypt the input file + +# Exercise 2 for page_num in range(0, input_file.getNumPages()): # rotate pages (call everything page_left for now; will make a copy) page_left = input_file.getPage(page_num) @@ -26,6 +31,8 @@ page_right.mediaBox.upperLeft = (upper_right[0] / 2, upper_right[1]) output_PDF.addPage(page_right) + +# Exercise 3 # save new pages to an output file output_file_name = os.path.join(path, "Output/Updated Walrus.pdf") with open(output_file_name, "wb") as output_file: diff --git a/chp11/solutions/cover_the_emperor.py b/ch12-interact-with-pdf-files/solutions/1-12-2.py similarity index 90% rename from chp11/solutions/cover_the_emperor.py rename to ch12-interact-with-pdf-files/solutions/1-12-2.py index aa6526d..6ab157f 100755 --- a/chp11/solutions/cover_the_emperor.py +++ b/ch12-interact-with-pdf-files/solutions/1-12-2.py @@ -1,4 +1,7 @@ -# chapter 11 cover_the_emperor.py +# 1.12.2 - Assignment: Add a Cover Sheet to a PDF File +# Solution to assignment + + # Add a cover sheet to a PDF; save the full output as a new PDF import os diff --git a/chp12/12-1.py b/ch13-sql-database-connections/1-13-0.py similarity index 83% rename from chp12/12-1.py rename to ch13-sql-database-connections/1-13-0.py index feca314..b79465c 100755 --- a/chp12/12-1.py +++ b/ch13-sql-database-connections/1-13-0.py @@ -1,4 +1,5 @@ -# 12.1 review exercises +# 1.13.0 - SQL Database Connections +# Solutions to review exercises import sqlite3 @@ -6,9 +7,11 @@ with sqlite3.connect(':memory:') as connection: c = connection.cursor() + # Exercise 1 # Create a "Roster" table with Name, Species and IQ fields c.execute("CREATE TABLE Roster(Name TEXT, Species TEXT, IQ INT)") + # Exercise 2 # Add some data into the database roster_data = ( ("Jean-Baptiste Zorg", "Human", 122), @@ -17,10 +20,12 @@ ) c.executemany("INSERT INTO Roster VALUES(?, ?, ?)", roster_data) + # Exercise 3 # Update the Species of Korben Dallas to "Human" c.execute("UPDATE Roster SET Species=? WHERE Name=?", ('Human', 'Korben Dallas')) + # Exercise 4 # Display the names and IQs of everyone classified as Human c.execute("SELECT Name, IQ FROM Roster WHERE Species = 'Human'") for row in c.fetchall(): diff --git a/chp13/13-1.py b/ch14-interacting-with-the-web/1-14-1.py similarity index 87% rename from chp13/13-1.py rename to ch14-interacting-with-the-web/1-14-1.py index d6566d3..fecfd3e 100755 --- a/chp13/13-1.py +++ b/ch14-interacting-with-the-web/1-14-1.py @@ -1,12 +1,15 @@ -# 13.1 review exercises +# 1.14.1 - Scrape and Parse Text From Websites +# Solutions to review exercises from urllib.request import urlopen +# Exercise 1 # Get the full HTML from the "dionysus" page my_address = "https://realpython.com/practice/dionysus.html" html_page = urlopen(my_address) html_text = html_page.read().decode('utf-8') +# Exercise 2 # Get the "Name" and "Favorite Color" using find() for tag in ["Name: ", "Favorite Color: "]: tag_start = html_text.find(tag) + len(tag) @@ -15,6 +18,7 @@ print(html_text[tag_start:tag_start + tag_end].strip(" \n")) +# Exercise 3 # Get the "Name" and "Favorite Color" using regular expressions import re # Match anything up until a new line or HTML tag; non-greedy diff --git a/chp13/13-2.py b/ch14-interacting-with-the-web/1-14-2.py similarity index 82% rename from chp13/13-2.py rename to ch14-interacting-with-the-web/1-14-2.py index b660150..00359d6 100755 --- a/chp13/13-2.py +++ b/ch14-interacting-with-the-web/1-14-2.py @@ -1,8 +1,10 @@ -# 13.2 review exercises +# 1.14.2 - Use an HTML Parser to Scrape Websites +# Solutions to review exercises from urllib.request import urlopen from bs4 import BeautifulSoup +# Exercise 1 # Get the full HTML from the "profiles" page base_URL = "https://realpython.com/practice/" address = base_URL + "profiles.html" @@ -10,10 +12,13 @@ html_text = html_page.read().decode('utf-8') soup = BeautifulSoup(html_text) +# Exercise 2 # Parse out all the values of the page links for anchor in soup.find_all("a"): # Could also have used urlparse.urljoin() to get absolute URL link_address = base_URL + anchor["href"] + + # Exercise 3 # Display the text in the HTML page of each link link_page = urlopen(link_address) link_text = link_page.read().decode('utf-8') diff --git a/chp13/13-3.py b/ch14-interacting-with-the-web/1-14-3.py similarity index 86% rename from chp13/13-3.py rename to ch14-interacting-with-the-web/1-14-3.py index 1026647..0aec1d0 100644 --- a/chp13/13-3.py +++ b/ch14-interacting-with-the-web/1-14-3.py @@ -1,7 +1,9 @@ -# 13.3 review exercises +# 1.14.2 - Interact with HTML Forms +# Solutions to review exercises import mechanicalsoup +# Exercise 1 my_browser = mechanicalsoup.Browser() login_page = my_browser.get("https://realpython.com/practice/login.php") login_html = login_page.soup @@ -11,16 +13,22 @@ form.select("input")[0]["value"] = "zeus" form.select("input")[1]["value"] = "ThunderDude" -# submit form and show profile page title +# submit form profiles_page = my_browser.submit(form, login_page.url) + +# Exercise 2 +# show profile page title title = profiles_page.soup.title print("Title: ", title.text) +# Exercise 3 # navigate back to login page and show title login_page = my_browser.get("https://realpython.com/practice/login.php") login_title = login_page.soup.title print("Title: ", login_title.text) + +# Exercise 4 # submit form with incorrect values form = login_html.form form.select("input")[0]["value"] = "wrong" diff --git a/chp13/13-4.py b/ch14-interacting-with-the-web/1-14-4.py similarity index 91% rename from chp13/13-4.py rename to ch14-interacting-with-the-web/1-14-4.py index e5d6830..ea10681 100644 --- a/chp13/13-4.py +++ b/ch14-interacting-with-the-web/1-14-4.py @@ -1,4 +1,5 @@ -# 13.4 review exercises +# 1.14.4 - Interact With Website in Real-Time +# Solutions to review exercise from time import sleep import mechanicalsoup diff --git a/chp14/practice_files/pirates.csv b/ch15-scientific-computing-and-graphing/practice_files/pirates.csv similarity index 100% rename from chp14/practice_files/pirates.csv rename to ch15-scientific-computing-and-graphing/practice_files/pirates.csv diff --git a/chp14/solutions/14-1.py b/ch15-scientific-computing-and-graphing/solutions/1-15-1.py similarity index 79% rename from chp14/solutions/14-1.py rename to ch15-scientific-computing-and-graphing/solutions/1-15-1.py index 9b351a8..310af6e 100755 --- a/chp14/solutions/14-1.py +++ b/ch15-scientific-computing-and-graphing/solutions/1-15-1.py @@ -1,27 +1,34 @@ -# 14.1 review exercises +# 1.15.1 - Use NumPy for Matrix Manipulation +# Solutions to review exercises # Setup import numpy +# Exercise 1 # Create a 3x3 array of the number 3 through 11 using reshape() first_matrix = numpy.arange(3, 12) first_matrix = first_matrix.reshape(3, 3) +# Exercise 2 # Display the min, max and mean of all entries in the matrix print "Min is", first_matrix.min() print "Max is", first_matrix.max() print "Mean is", first_matrix.mean() +# Exercise 3 # Square every entry and save in a new matrix second_matrix = first_matrix ** 2 +# Exercise 4 # Put first_matrix on top of second_matrix third_matrix = numpy.vstack([first_matrix, second_matrix]) +# Exercise 5 # Calculate the dot product of third_matrix by first_matrix print(numpy.dot(third_matrix, first_matrix)) +# Exercise 6 # Reshape third_matrix into a 3x3x2 matrix third_matrix = third_matrix.reshape(3, 3, 2) print(third_matrix) diff --git a/chp14/solutions/pirates.py b/ch15-scientific-computing-and-graphing/solutions/1-15-2.py similarity index 85% rename from chp14/solutions/pirates.py rename to ch15-scientific-computing-and-graphing/solutions/1-15-2.py index 38b5e72..0da8471 100755 --- a/chp14/solutions/pirates.py +++ b/ch15-scientific-computing-and-graphing/solutions/1-15-2.py @@ -1,9 +1,13 @@ -# chapter 14 pirates.py +# 1.15.2 - Use matplotlib for Plotting Graphs +# Solution to review exercise #2 + # Graph pirates versus global warming from matplotlib import pyplot as plt import csv import os + +# Change `path` to actual path on your system path = "C:/Real Python/refactor/chp15/practice_files" years = [] diff --git a/chp15/partial_PDF.py b/ch16-graphical-user-interface/1-16-2.py similarity index 94% rename from chp15/partial_PDF.py rename to ch16-graphical-user-interface/1-16-2.py index f79ac1c..a1bc468 100755 --- a/chp15/partial_PDF.py +++ b/ch16-graphical-user-interface/1-16-2.py @@ -1,4 +1,6 @@ -# chapter 15 partial_PDF.py +# 1.16.2 - Assignment: Use GUI Elements to Help a User Modify Files +# Solution to assignment + # save part of a PDF based on a user-supplied page range using a GUI from easygui import * diff --git a/chp15/15-1.py b/ch16-graphical-user-interface/1-16-3.py similarity index 80% rename from chp15/15-1.py rename to ch16-graphical-user-interface/1-16-3.py index 8ee07df..2a22d5b 100755 --- a/chp15/15-1.py +++ b/ch16-graphical-user-interface/1-16-3.py @@ -1,4 +1,5 @@ -# 15.1 review exercises +# 1.16.3- Create GUI Application with Tkinter +# Solutions to review exercise #2 # Create a button that takes on the value in an entry box @@ -10,6 +11,7 @@ def button_clicked(): ''' sets the button text to the text in the entry box ''' button.config(text=entry.get()) + window = Tk() # Create and add button button = Button(text=" ", command=button_clicked) diff --git a/chp15/poetry_writer.py b/ch16-graphical-user-interface/poetry_writer.py similarity index 100% rename from chp15/poetry_writer.py rename to ch16-graphical-user-interface/poetry_writer.py diff --git a/chp01/1-2.py b/chp01/1-2.py deleted file mode 100755 index 118a3b0..0000000 --- a/chp01/1-2.py +++ /dev/null @@ -1,13 +0,0 @@ -# chapter 1 review exercises - -# The following lines can also be typed -# directly into the interactive window as well: - - -# display a string directly -print("hello") - - -# display the contents of a string variable -my_string = "hi" -print(my_string) diff --git a/chp03/3-1.py b/chp03/3-1.py deleted file mode 100755 index fe172a6..0000000 --- a/chp03/3-1.py +++ /dev/null @@ -1,11 +0,0 @@ -# 3.1 review exercises - -print('There are "double quotes" in this string.') - -print("This string's got an apostrophe.") - -print('''This string was written on multiple lines, -and it displays across multiple lines''') - -print("This one-line string was written out \ -using multiple lines") diff --git a/chp08/list_of_lists.py b/chp08/list_of_lists.py deleted file mode 100644 index 4f5ca34..0000000 --- a/chp08/list_of_lists.py +++ /dev/null @@ -1,58 +0,0 @@ -def enrollment_stats(list_of_universities): - - # variables - total_students = [] - total_tuition = [] - - # iterate through lists, adding values - for university in list_of_universities: - total_students.append(university[1]) - total_tuition.append(university[2]) - - # return variables - return total_students, total_tuition - - -def mean(my_list): - if len(my_list) == 0: - return 'The list is empty' - list_sum = 0 - for i in range(len(my_list)): - list_sum += float(my_list[i]) - return int(list_sum / len(my_list)) - - -def median(my_list): - sorts = sorted(my_list) - length = len(sorts) - if not length % 2: - return (sorts[int(length / 2)] + sorts[int(length / 2 - 1)]) / 2.0 - return sorts[int(length / 2)] - - -if __name__ == '__main__': - - universities = [ - ['California Institute of Technology', 2175, 37704], - ['Harvard', 19627, 39849], - ['Massachusetts Institute of Technology', 10566, 40732], - ['Princeton', 7802, 37000], - ['Rice', 5879, 35551], - ['Stanford', 19535, 40569], - ['Yale', 11701, 40500], - ] - - totals = enrollment_stats(universities) - - print(totals[0]) - - print("\n") - print("*****" * 5) - print("Total students: {}".format(sum(totals[0]))) - print("Total tuition: $ {}".format(sum(totals[1]))) - print("\nStudent mean: {}".format(mean(totals[0]))) - print("Student median: {}".format(median(totals[0]))) - print("\nTuition mean: $ {}".format(mean(totals[1]))) - print("Tuition median: $ {}".format(median(totals[1]))) - print("*****" * 5) - print("\n")