diff --git a/.gitignore b/.gitignore index ad46379..981b13d 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,5 @@ __pycache__/ .DS_Store .vscode venv +.venv .idea/* diff --git a/README.md b/README.md index c88387e..06929d4 100755 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ In this code repository you find the solutions and sample implementations for the solutions and challenges posed in our [Python Basics](https://realpython.com/products/python-basics-book/) book. All solutions and sample files are ordered by chapter so you can quickly navigate to the code you're looking for. +In most cases, the solutions presented here represent just one way out of many that the exercises and challenges can be solved. If you find a better way to solve one of the exercises or challenges feel free to open an issue or pull request! + ## Get the Book [ยป Click here to learn more about the book and get your copy](https://realpython.com/products/python-basics-book/) @@ -32,4 +34,4 @@ hello hi ``` -> **Note:** Depending on your installation, you may need to type `python3.7` or `python37` to run the examples. +> **Note:** Depending on your installation, you may need to type `python3.9` or `python39` to run the examples. diff --git a/ch04-strings-and-string-methods/3-manipulate-strings-with-methods.py b/ch04-strings-and-string-methods/3-manipulate-strings-with-methods.py index a37fed6..79b6279 100644 --- a/ch04-strings-and-string-methods/3-manipulate-strings-with-methods.py +++ b/ch04-strings-and-string-methods/3-manipulate-strings-with-methods.py @@ -27,7 +27,7 @@ string3 = " Cheeseburger " print(string1.strip()) # Could also use .lstrip() -print(string1.strip()) # Could also use .rstrip() +print(string2.strip()) # Could also use .rstrip() print(string3.strip()) diff --git a/ch04-strings-and-string-methods/5-challenge-pick-apart-your-users-input.py b/ch04-strings-and-string-methods/5-challenge-pick-apart-your-users-input.py index c045b1b..2079edd 100644 --- a/ch04-strings-and-string-methods/5-challenge-pick-apart-your-users-input.py +++ b/ch04-strings-and-string-methods/5-challenge-pick-apart-your-users-input.py @@ -6,4 +6,4 @@ user_input = input("Tell me your password: ") first_letter = user_input[0] -print("The first letter you entered was:", first_letter.upper()) +print("The first letter you entered was: " + first_letter.upper()) diff --git a/ch04-strings-and-string-methods/6-working-with-strings-and-numbers.py b/ch04-strings-and-string-methods/6-working-with-strings-and-numbers.py index 10c2a23..9b4ca3a 100644 --- a/ch04-strings-and-string-methods/6-working-with-strings-and-numbers.py +++ b/ch04-strings-and-string-methods/6-working-with-strings-and-numbers.py @@ -28,9 +28,9 @@ # Exercise 4 -# Get two numbers from the user, multiple them, +# Get two numbers from the user, multiply them, # and display the result a = input("Enter a number: ") b = input("Enter another number: ") product = float(a) * float(b) -print("The product of " + a + " and " + b + " is " + str(product)) +print("The product of " + a + " and " + b + " is " + str(product) + ".") diff --git a/ch04-strings-and-string-methods/7-streamline-your-print-statements.py b/ch04-strings-and-string-methods/7-streamline-your-prints.py similarity index 81% rename from ch04-strings-and-string-methods/7-streamline-your-print-statements.py rename to ch04-strings-and-string-methods/7-streamline-your-prints.py index 18c29c4..d89832c 100644 --- a/ch04-strings-and-string-methods/7-streamline-your-print-statements.py +++ b/ch04-strings-and-string-methods/7-streamline-your-prints.py @@ -1,4 +1,4 @@ -# 4.7 - Streamline Your Print Statements +# 4.7 - Streamline Your Prints # Solutions to review exercies @@ -6,7 +6,7 @@ weight = 0.2 animal = "newt" -# Concatenate a number and a string in one print statement +# Concatenate a number and a string in one print call print(str(weight) + " kg is the weight of the " + animal + ".") diff --git a/ch06-functions-and-loops/2-write-your-own-functions.py b/ch06-functions-and-loops/2-write-your-own-functions.py index d21c159..ac29db5 100644 --- a/ch06-functions-and-loops/2-write-your-own-functions.py +++ b/ch06-functions-and-loops/2-write-your-own-functions.py @@ -5,7 +5,7 @@ # Exercise 1 def cube(num): """Return the cube of the input number.""" - cube_num = num ** 3 # Could also use pow(num, 3) + cube_num = num**3 # Could also use pow(num, 3) return cube_num diff --git a/ch06-functions-and-loops/5-challenge-track-your-investments.py b/ch06-functions-and-loops/5-challenge-track-your-investments.py index 98964f7..0041382 100644 --- a/ch06-functions-and-loops/5-challenge-track-your-investments.py +++ b/ch06-functions-and-loops/5-challenge-track-your-investments.py @@ -6,6 +6,7 @@ def invest(amount, rate, years): + """Display year on year growth of an initial investment""" for year in range(1, years + 1): amount = amount * (1 + rate) print(f"year {year}: ${amount:,.2f}") diff --git a/ch08-conditional-logic/2-add-some-logic.py b/ch08-conditional-logic/2-add-some-logic.py index 2880c21..e7bd650 100644 --- a/ch08-conditional-logic/2-add-some-logic.py +++ b/ch08-conditional-logic/2-add-some-logic.py @@ -1,14 +1,14 @@ # 8.2 - Add Some Logic # Solutions to review exercises -# --- Exercise 1 +# Exercise 1 # Test whether these expressions are True or False print((1 <= 1) and (1 != 1)) print(not (1 != 2)) print(("good" != "bad") or False) print(("good" != "Good") and not (1 == 1)) -# --- Exercise 2 +# Exercise 2 # Add parentheses so that the following expressions all # evaluate to True diff --git a/ch08-conditional-logic/3-control-the-flow-of-your-program.py b/ch08-conditional-logic/3-control-the-flow-of-your-program.py index 2f19b72..6e81837 100644 --- a/ch08-conditional-logic/3-control-the-flow-of-your-program.py +++ b/ch08-conditional-logic/3-control-the-flow-of-your-program.py @@ -2,6 +2,7 @@ # Solutions to review exercises +# Exercise 1 # Display whether the length of user input is <, > or = 5 characters my_input = input("Type something: ") @@ -12,3 +13,15 @@ print("Your input is greater than 5 characters long.") else: print("Your input is 5 characters long.") + + +# Exercise 2 +# Number guessing program ("guess" the number 3) + +print("I'm thinking of a number between 1 and 10. Guess which one.") +my_guess = input("Type in your guess: ") + +if my_guess == "3": + print("You win!") +else: + print("You lose.") diff --git a/ch08-conditional-logic/6-recover-from-errors.py b/ch08-conditional-logic/6-recover-from-errors.py index 157536d..250144b 100644 --- a/ch08-conditional-logic/6-recover-from-errors.py +++ b/ch08-conditional-logic/6-recover-from-errors.py @@ -15,7 +15,7 @@ # Exercise 2 -# Print character and specifid index in string +# Print character and specified index in string input_string = input("Enter a string: ") diff --git a/ch08-conditional-logic/7-simulate-events-and-calculate-probabilities.py b/ch08-conditional-logic/7-simulate-events-and-calculate-probabilities.py index 29de41f..d7b939f 100644 --- a/ch08-conditional-logic/7-simulate-events-and-calculate-probabilities.py +++ b/ch08-conditional-logic/7-simulate-events-and-calculate-probabilities.py @@ -6,7 +6,7 @@ # Exercise 1 -# Write a function that simulatee the roll of a die. +# Write a function that simulates the roll of a die. def roll(): """Return random integer between 1 and 6""" return randint(1, 6) diff --git a/ch08-conditional-logic/8b-challenge-simulate-a-coin-toss-experiment.py b/ch08-conditional-logic/8b-challenge-simulate-a-coin-toss-experiment.py index a01a8ce..9f3effe 100644 --- a/ch08-conditional-logic/8b-challenge-simulate-a-coin-toss-experiment.py +++ b/ch08-conditional-logic/8b-challenge-simulate-a-coin-toss-experiment.py @@ -31,7 +31,7 @@ def coin_flip(): first_flip = coin_flip() flips = flips + 1 # Continue flipping the coin and updating the tally until - # a different result is returned by coin_flips() + # a different result is returned by coin_flip() while coin_flip() == first_flip: flips = flips + 1 # Increment the flip tally once more to account for the diff --git a/ch08-conditional-logic/8c-challenge-simulate-a-coin-toss-experiment.py b/ch08-conditional-logic/8c-challenge-simulate-a-coin-toss-experiment.py index a652fbb..753e91d 100644 --- a/ch08-conditional-logic/8c-challenge-simulate-a-coin-toss-experiment.py +++ b/ch08-conditional-logic/8c-challenge-simulate-a-coin-toss-experiment.py @@ -12,26 +12,38 @@ # 4. After the first toss, you'll need another loop to keep flipping while you # get the same result as the first flip. -from random import randint +import random def single_trial(): - toss = randint(0, 1) - total_flips = 1 + """Simulate repeatedly flipping a coin until both heads and tails are seen.""" + # This function uses random.randint() to simulate a single coin toss. + # randint(0, 1) randomly returns 0 or 1 with equal probability. We can + # use 0 to represent heads and 1 to represent tails. - while toss == randint(0, 1): - total_flips += 1 - toss = randint(0, 1) + # Flip the coin the first time + flip_result = random.randint(0, 1) + # Keep a tally of how many times the coin has been flipped. We've only + # flipped once so the initial count is 1. + flip_count = 1 - total_flips += 1 - return total_flips + # Continue to flip the coin until randint(0, 1) returns something + # different than the original flip_result + while flip_result == random.randint(0, 1): + flip_count = flip_count + 1 + + # The last step in the loop flipped the coin but didn't update the tally, + # so we need to increase the flip_count by 1 + flip_count = flip_count + 1 + return flip_count def flip_trial_avg(num_trials): + """Calculate the average number of flips per trial over num_trials total trials.""" total = 0 for trial in range(num_trials): - total += single_trial() + total = total + single_trial() return total / num_trials -print(f"The average number of coin flips was {flip_trial_avg(10000)}") +print(f"The average number of coin flips was {flip_trial_avg(10_000)}") diff --git a/ch08-conditional-logic/9a-challenge-simulate-an-election.py b/ch08-conditional-logic/9a-challenge-simulate-an-election.py index 5d6f04d..a9ef523 100644 --- a/ch08-conditional-logic/9a-challenge-simulate-an-election.py +++ b/ch08-conditional-logic/9a-challenge-simulate-an-election.py @@ -10,7 +10,7 @@ num_times_B_wins = 0 num_trials = 10_000 -for trial in range(0,num_trials): +for trial in range(0, num_trials): votes_for_A = 0 votes_for_B = 0 @@ -26,7 +26,7 @@ else: votes_for_B = votes_for_B + 1 - # Determine who wins the erd region + # Determine who wins the 3rd region if random() < 0.17: votes_for_A = votes_for_A + 1 else: diff --git a/ch08-conditional-logic/9b-challenge-simulate-an-election.py b/ch08-conditional-logic/9b-challenge-simulate-an-election.py index 63364f3..eb45794 100644 --- a/ch08-conditional-logic/9b-challenge-simulate-an-election.py +++ b/ch08-conditional-logic/9b-challenge-simulate-an-election.py @@ -37,7 +37,8 @@ def run_election(regional_chances): # "B" is the total number of regions minus the number of regions won by # candidate "A". The total number of regions is the same as the length # of the regional_chances list. - if num_regions_won_by_A > len(regional_chances) - num_regions_won_by_A: + num_regions_won_by_B = len(regional_chances) - num_regions_won_by_A + if num_regions_won_by_A > num_regions_won_by_B: return "A" else: return "B" @@ -55,5 +56,5 @@ def run_election(regional_chances): # Display the probabilities that candidate A or candidate B wins the # election. Note the probability that B wins can be calculated by # subtracting the probability that A wins from 1. -print(f"Probability A wins: {num_times_A_wins / num_trials}") -print(f"Probability B wins: {1 - (num_times_A_wins / num_trials)}") +print(f"Probability A wins: {num_times_A_wins / NUM_TRIALS}") +print(f"Probability B wins: {1 - (num_times_A_wins / NUM_TRIALS)}") diff --git a/ch09-lists-tuples-and-dictionaries/1-tuples-are-immutable-sequences.py b/ch09-lists-tuples-and-dictionaries/1-tuples-are-immutable-sequences.py index 96d6ad8..1b0bcf0 100644 --- a/ch09-lists-tuples-and-dictionaries/1-tuples-are-immutable-sequences.py +++ b/ch09-lists-tuples-and-dictionaries/1-tuples-are-immutable-sequences.py @@ -13,7 +13,7 @@ # Exercise 3 -# unpack the tuple into three string and display them +# Unpack the tuple into three strings and display them position1, position2, position3 = cardinal_numbers print(position1) print(position2) @@ -23,7 +23,7 @@ # Create a tuple containing the letters of your name from a string my_name = tuple("David") -# Exercide 5 +# Exercise 5 # Check whether or not x is in my_name print("x" in my_name) diff --git a/ch09-lists-tuples-and-dictionaries/2-lists-are-mutable-sequences.py b/ch09-lists-tuples-and-dictionaries/2-lists-are-mutable-sequences.py index 311fdb4..6151b2b 100644 --- a/ch09-lists-tuples-and-dictionaries/2-lists-are-mutable-sequences.py +++ b/ch09-lists-tuples-and-dictionaries/2-lists-are-mutable-sequences.py @@ -8,8 +8,8 @@ # Exercise 2 -# Append the string "broccolo" to the food list using .append() -food.append("brocolli") +# Append the string "broccoli" to the food list using .append() +food.append("broccoli") # Exercise 3 diff --git a/ch09-lists-tuples-and-dictionaries/3-nesting-sorting-and-copying-lists-and-tuples.py b/ch09-lists-tuples-and-dictionaries/3-nesting-sorting-and-copying-lists-and-tuples.py index f9a3121..a7604b3 100644 --- a/ch09-lists-tuples-and-dictionaries/3-nesting-sorting-and-copying-lists-and-tuples.py +++ b/ch09-lists-tuples-and-dictionaries/3-nesting-sorting-and-copying-lists-and-tuples.py @@ -8,9 +8,11 @@ # Exercise 2 -# Loop over data a print the sum of each nested tuple -for i in range(len(data)): - print(f"Row {i+1} sum: {data[i][0] + data[i][1]}") +# Loop over data and print the sum of each nested tuple +index = 1 +for row in data: + print(f"Row {index} sum: {sum(row)}") + index += 1 # Exercise 3 diff --git a/ch09-lists-tuples-and-dictionaries/4-challenge-list-of-lists.py b/ch09-lists-tuples-and-dictionaries/4-challenge-list-of-lists.py index 48f22dd..f723245 100644 --- a/ch09-lists-tuples-and-dictionaries/4-challenge-list-of-lists.py +++ b/ch09-lists-tuples-and-dictionaries/4-challenge-list-of-lists.py @@ -3,7 +3,6 @@ def enrollment_stats(list_of_universities): - # Variables total_students = [] total_tuition = [] @@ -25,7 +24,7 @@ def mean(values): def median(values): """Return the median value of the list `values`""" values.sort() - # If the number of valus is odd, + # If the number of values is odd, # return the middle value of the list if len(values) % 2 == 1: # The value at the center of the list is the value @@ -36,8 +35,8 @@ def median(values): # Otherwise, if the length of the list is even, return # the mean of the two center values else: - left_center_index = (len(values) - 1) / 2 - right_center_index = (len(values) + 1) / 2 + left_center_index = (len(values) - 1) // 2 + right_center_index = (len(values) + 1) // 2 return mean([values[left_center_index], values[right_center_index]]) diff --git a/ch09-lists-tuples-and-dictionaries/5-challenge-wax-poetic.py b/ch09-lists-tuples-and-dictionaries/5-challenge-wax-poetic.py index b6384a8..7b9ed8a 100644 --- a/ch09-lists-tuples-and-dictionaries/5-challenge-wax-poetic.py +++ b/ch09-lists-tuples-and-dictionaries/5-challenge-wax-poetic.py @@ -4,7 +4,7 @@ # Generate a random poem based on a set structure -from random import choice +import random noun = [ "fossil", @@ -57,54 +57,57 @@ def make_poem(): """Create a randomly generated poem, returned as a multi-line string.""" # Pull three nouns randomly - n1 = choice(noun) - n2 = choice(noun) - n3 = choice(noun) + n1 = random.choice(noun) + n2 = random.choice(noun) + n3 = random.choice(noun) # Make sure that all the nouns are different while n1 == n2: - n2 = choice(noun) + n2 = random.choice(noun) while n1 == n3 or n2 == n3: - n3 = choice(noun) + n3 = random.choice(noun) # Pull three different verbs - v1 = choice(verb) - v2 = choice(verb) - v3 = choice(verb) + v1 = random.choice(verb) + v2 = random.choice(verb) + v3 = random.choice(verb) while v1 == v2: - v2 = choice(verb) + v2 = random.choice(verb) while v1 == v3 or v2 == v3: - v3 = choice(verb) + v3 = random.choice(verb) # Pull three different adjectives - adj1 = choice(adjective) - adj2 = choice(adjective) - adj3 = choice(adjective) + adj1 = random.choice(adjective) + adj2 = random.choice(adjective) + adj3 = random.choice(adjective) while adj1 == adj2: - adj2 = choice(adjective) + adj2 = random.choice(adjective) while adj1 == adj3 or adj2 == adj3: - adj3 = choice(adjective) + adj3 = random.choice(adjective) # Pull two different prepositions - prep1 = choice(preposition) - prep2 = choice(preposition) + prep1 = random.choice(preposition) + prep2 = random.choice(preposition) while prep1 == prep2: - prep2 = choice(preposition) + prep2 = random.choice(preposition) # Pull one adverb - adv1 = choice(adverb) + adv1 = random.choice(adverb) - if "aeiou".find(adj1[0]) != -1: # first letter is a vowel + if "aeiou".find(adj1[0]) != -1: # First letter is a vowel article = "An" else: article = "A" - # add lines to poem - poem = f"{article} {adj1} {n1}\n\n" - poem = poem + f"{article} {adj1} {n1} {v1} {prep1} the {adj2} {n2}\n" - poem = poem + f"{adv1}, the {n1} {v2}\n" - poem = poem + f"the {n2} {v3} {prep2} a {adj3} {n3}" + # Create the poem + poem = ( + f"{article} {adj1} {n1}\n\n" + f"{article} {adj1} {n1} {v1} {prep1} the {adj2} {n2}\n" + f"{adv1}, the {n1} {v2}\n" + f"the {n2} {v3} {prep2} a {adj3} {n3}" + ) return poem -print(make_poem()) +poem = make_poem() +print(poem) diff --git a/ch09-lists-tuples-and-dictionaries/6-store-relationships-in-dictionaries.py b/ch09-lists-tuples-and-dictionaries/6-store-relationships-in-dictionaries.py index 89002d9..2d4509e 100644 --- a/ch09-lists-tuples-and-dictionaries/6-store-relationships-in-dictionaries.py +++ b/ch09-lists-tuples-and-dictionaries/6-store-relationships-in-dictionaries.py @@ -22,7 +22,7 @@ captains["Discovery"] = "unknown" # Bonus points: you could instead loop over a list of names to check -# for name in ["Enterprise", "Discovery"]: +# for ship in ["Enterprise", "Discovery"]: # if not ship in captains: # captains[ship] = "unknown" diff --git a/ch09-lists-tuples-and-dictionaries/7-challenge-capital-city-loop.py b/ch09-lists-tuples-and-dictionaries/7-challenge-capital-city-loop.py index d662974..8eca70b 100644 --- a/ch09-lists-tuples-and-dictionaries/7-challenge-capital-city-loop.py +++ b/ch09-lists-tuples-and-dictionaries/7-challenge-capital-city-loop.py @@ -56,8 +56,11 @@ "Wyoming": "Cheyenne", } +# Pull random state and capital pair from the dict by casting to list of tuples state, capital = random.choice(list(capitals_dict.items())) +# Game loop continues until the user inputs "exit" +# or guesses the correct capital while True: guess = input(f"What is the capital of '{state}'? ").lower() if guess == "exit": diff --git a/ch09-lists-tuples-and-dictionaries/9a-challenge-cats-with-hats.py b/ch09-lists-tuples-and-dictionaries/9a-challenge-cats-with-hats.py index 3e081c0..74cb1ed 100644 --- a/ch09-lists-tuples-and-dictionaries/9a-challenge-cats-with-hats.py +++ b/ch09-lists-tuples-and-dictionaries/9a-challenge-cats-with-hats.py @@ -4,18 +4,30 @@ def get_cats_with_hats(array_of_cats): cats_with_hats_on = [] + # We want to walk around the circle 100 times for num in range(1, 100 + 1): + # Each time we walk around, we visit 100 cats for cat in range(1, 100 + 1): + # Determine whether to visit the cat + # Use modulo operator to visit every 2nd, 3rd, 4th,... etc. if cat % num == 0: + # Remove or add hat depending on + # whether the cat already has one if array_of_cats[cat] is True: array_of_cats[cat] = False else: array_of_cats[cat] = True + + # Add all number of each cat with a hat to list for cat in range(1, 100 + 1): - if cats[cat] is True: + if array_of_cats[cat] is True: cats_with_hats_on.append(cat) + + # Return the resulting list return cats_with_hats_on +# Cats contains whether each cat already has a hat on, +# by default all are set to false since none have been visited cats = [False] * (100 + 1) print(get_cats_with_hats(cats)) diff --git a/ch09-lists-tuples-and-dictionaries/9c-challenge-cats-with-hats.py b/ch09-lists-tuples-and-dictionaries/9c-challenge-cats-with-hats.py index c154a31..1e4c885 100644 --- a/ch09-lists-tuples-and-dictionaries/9c-challenge-cats-with-hats.py +++ b/ch09-lists-tuples-and-dictionaries/9c-challenge-cats-with-hats.py @@ -4,17 +4,24 @@ theCats = {} +# By default, no cats have been visited +# so we set every cat's number to False for i in range(1, 101): theCats[i] = False +# Walk around the circle 100 times for i in range(1, 101): + # Visit all cats each time we do a lap for cats, hats in theCats.items(): + # Determine whether or not we visit a cat if cats % i == 0: + # Add or remove the hat if theCats[cats]: theCats[cats] = False else: theCats[cats] = True +# Print whether each cat has a hat for cats, hats in theCats.items(): if theCats[cats]: print(f"Cat {cats} has a hat.") diff --git a/ch10-primer-on-oop/3-inherit-from-other-classes.py b/ch10-primer-on-oop/3-inherit-from-other-classes.py index fc9a395..36efe49 100644 --- a/ch10-primer-on-oop/3-inherit-from-other-classes.py +++ b/ch10-primer-on-oop/3-inherit-from-other-classes.py @@ -39,5 +39,9 @@ class Square(Rectangle): def __init__(self, side_length): super().__init__(side_length, side_length) + square = Square(4) -print(square.area()) +print(square.area()) # 16 + +square.width = 5 # Modifies .width but not .length +print(square.area()) # 20 diff --git a/ch11-modules-and-packages/1-working-with-modules/greeter.py b/ch11-modules-and-packages/1-working-with-modules/greeter.py new file mode 100644 index 0000000..436349b --- /dev/null +++ b/ch11-modules-and-packages/1-working-with-modules/greeter.py @@ -0,0 +1,6 @@ +# Ch 11.1 - Modules and Packages +# Solution to Exercise 1 + + +def greet(name): + print(f"Hello {name}!") diff --git a/ch11-modules-and-packages/1-working-with-modules/main.py b/ch11-modules-and-packages/1-working-with-modules/main.py new file mode 100644 index 0000000..13cc631 --- /dev/null +++ b/ch11-modules-and-packages/1-working-with-modules/main.py @@ -0,0 +1,7 @@ +# Ch 11.1 - Modules and Packages +# Solution to Exercise 2 + +import greeter + + +greeter.greet("Real Python") diff --git a/ch11-modules-and-packages/2-working-with-packages/packages_exercises/helpers/__init__.py b/ch11-modules-and-packages/2-working-with-packages/packages_exercises/helpers/__init__.py new file mode 100644 index 0000000..6ea23c6 --- /dev/null +++ b/ch11-modules-and-packages/2-working-with-packages/packages_exercises/helpers/__init__.py @@ -0,0 +1,2 @@ +# Ch 11.2 - Working With Packages +# __init__.py - Part of solution to Exercise 1 diff --git a/ch11-modules-and-packages/2-working-with-packages/packages_exercises/helpers/math.py b/ch11-modules-and-packages/2-working-with-packages/packages_exercises/helpers/math.py new file mode 100644 index 0000000..745c003 --- /dev/null +++ b/ch11-modules-and-packages/2-working-with-packages/packages_exercises/helpers/math.py @@ -0,0 +1,6 @@ +# Ch 11.2 - Working With Packages +# helpers/math.py - Part of solution to Exercise 1 + + +def area(length, width): + return length * width diff --git a/ch11-modules-and-packages/2-working-with-packages/packages_exercises/helpers/string.py b/ch11-modules-and-packages/2-working-with-packages/packages_exercises/helpers/string.py new file mode 100644 index 0000000..a6480aa --- /dev/null +++ b/ch11-modules-and-packages/2-working-with-packages/packages_exercises/helpers/string.py @@ -0,0 +1,6 @@ +# Ch 11.2 - Working With Packages +# helpers/string.py - Part of solution to Exercise 1 + + +def shout(string): + return string.upper() diff --git a/ch11-modules-and-packages/2-working-with-packages/packages_exercises/main.py b/ch11-modules-and-packages/2-working-with-packages/packages_exercises/main.py new file mode 100644 index 0000000..33c8648 --- /dev/null +++ b/ch11-modules-and-packages/2-working-with-packages/packages_exercises/main.py @@ -0,0 +1,11 @@ +# Ch 11.2 - Working With Packages +# main.py - Solution to Exercise 2 + +from helpers.string import shout +from helpers.math import area + + +length = 5 +width = 8 +message = f"The area of a {length}-by-{width} rectangle is {area(length, width)}" +print(shout(message)) diff --git a/ch11-file-input-and-output/2-working-with-file-paths-in-python.py b/ch12-file-input-and-output/2-working-with-file-paths-in-python.py similarity index 85% rename from ch11-file-input-and-output/2-working-with-file-paths-in-python.py rename to ch12-file-input-and-output/2-working-with-file-paths-in-python.py index 86e2a21..8726232 100644 --- a/ch11-file-input-and-output/2-working-with-file-paths-in-python.py +++ b/ch12-file-input-and-output/2-working-with-file-paths-in-python.py @@ -1,4 +1,4 @@ -# 11.2 - Working With File Paths in Python +# 12.2 - Working With File Paths in Python # Solutions to review exercises diff --git a/ch11-file-input-and-output/3-common-file-system-operations.py b/ch12-file-input-and-output/3-common-file-system-operations.py similarity index 89% rename from ch11-file-input-and-output/3-common-file-system-operations.py rename to ch12-file-input-and-output/3-common-file-system-operations.py index 2633350..eaf8042 100644 --- a/ch11-file-input-and-output/3-common-file-system-operations.py +++ b/ch12-file-input-and-output/3-common-file-system-operations.py @@ -1,4 +1,4 @@ -# 11.3 Common File System Operations +# 12.3 Common File System Operations # Solutions to Exercises @@ -29,6 +29,7 @@ file1.unlink() -# # Exercise 5 +# Exercise 5 import shutil + shutil.rmtree(new_dir) diff --git a/ch11-file-input-and-output/4-challenge-move-all-image-files-to-a-new-directory.py b/ch12-file-input-and-output/4-challenge-move-all-image-files-to-a-new-directory.py similarity index 69% rename from ch11-file-input-and-output/4-challenge-move-all-image-files-to-a-new-directory.py rename to ch12-file-input-and-output/4-challenge-move-all-image-files-to-a-new-directory.py index 82ea7b4..b39266c 100644 --- a/ch11-file-input-and-output/4-challenge-move-all-image-files-to-a-new-directory.py +++ b/ch12-file-input-and-output/4-challenge-move-all-image-files-to-a-new-directory.py @@ -1,16 +1,10 @@ -# 11.4 Challenge: Move All Image Files To a New Directory +# 12.4 Challenge: Move All Image Files To a New Directory # Solution to Challenge from pathlib import Path # Change this path to match the location on your computer -documents_dir = ( - Path.home() / - "python-basics-exercises" / - "ch11-file-input-and-output" / - "practice_files" / - "documents" -) +documents_dir = Path.cwd() / "practice_files" / "documents" # Create an images/ directory in your home directory images_dir = Path.home() / "images" diff --git a/ch11-file-input-and-output/5-reading-and-writing-files.py b/ch12-file-input-and-output/5-reading-and-writing-files.py similarity index 94% rename from ch11-file-input-and-output/5-reading-and-writing-files.py rename to ch12-file-input-and-output/5-reading-and-writing-files.py index 498791a..2dd4f0c 100644 --- a/ch11-file-input-and-output/5-reading-and-writing-files.py +++ b/ch12-file-input-and-output/5-reading-and-writing-files.py @@ -1,4 +1,4 @@ -# 11.5 - Reading and Writing Files +# 12.5 - Reading and Writing Files # Solutions to Exercises diff --git a/ch11-file-input-and-output/6-read-and-write-csv-data.py b/ch12-file-input-and-output/6-read-and-write-csv-data.py similarity index 97% rename from ch11-file-input-and-output/6-read-and-write-csv-data.py rename to ch12-file-input-and-output/6-read-and-write-csv-data.py index 5114e2f..233b1d4 100644 --- a/ch11-file-input-and-output/6-read-and-write-csv-data.py +++ b/ch12-file-input-and-output/6-read-and-write-csv-data.py @@ -1,4 +1,4 @@ -# 11.5 Read and Write CSV Data +# 12.5 Read and Write CSV Data # Solutions to Exercises diff --git a/ch11-file-input-and-output/7-challenge-create-a-high-scores-list.py b/ch12-file-input-and-output/7-challenge-create-a-high-scores-list.py similarity index 81% rename from ch11-file-input-and-output/7-challenge-create-a-high-scores-list.py rename to ch12-file-input-and-output/7-challenge-create-a-high-scores-list.py index ee8a9a1..f9539f8 100644 --- a/ch11-file-input-and-output/7-challenge-create-a-high-scores-list.py +++ b/ch12-file-input-and-output/7-challenge-create-a-high-scores-list.py @@ -1,4 +1,4 @@ -# 11.7 Challenge: Create a High Scores List +# 12.7 Challenge: Create a High Scores List # Solution to Challenge import csv @@ -6,12 +6,9 @@ # Change the path below to match the location on your computer scores_csv_path = ( - Path.home() / - "github/realpython" / - "python-basics-exercises" / - "ch11-file-input-and-output" / - "practice_files" / - "scores.csv" + Path.cwd() + / "practice_files" + / "scores.csv" ) with scores_csv_path.open(mode="r", encoding="utf-8") as file: @@ -21,7 +18,7 @@ high_scores = {} for item in scores: name = item["name"] - score = item["score"] + score = int(item["score"]) # If the name has not been added to the high_score dictionary, then # create a new key with the name and set its value to the score if name not in high_scores: @@ -35,9 +32,10 @@ # The high_scores dictionary now contains one key for each name that was # in the scores.csv file, and each value is that player's highest score. -output_csv_file = Path.home() / "high_scores.csv" +output_csv_file = Path.cwd() / "high_scores.csv" with output_csv_file.open(mode="w", encoding="utf-8") as file: writer = csv.DictWriter(file, fieldnames=["name", "high_score"]) + writer.writeheader() for name in high_scores: row_dict = {"name": name, "high_score": high_scores[name]} writer.writerow(row_dict) diff --git a/ch11-file-input-and-output/practice_files/documents/files/additional files/image3.png b/ch12-file-input-and-output/practice_files/documents/files/additional files/image3.png similarity index 100% rename from ch11-file-input-and-output/practice_files/documents/files/additional files/image3.png rename to ch12-file-input-and-output/practice_files/documents/files/additional files/image3.png diff --git a/ch11-file-input-and-output/practice_files/documents/files/dad.txt b/ch12-file-input-and-output/practice_files/documents/files/dad.txt similarity index 100% rename from ch11-file-input-and-output/practice_files/documents/files/dad.txt rename to ch12-file-input-and-output/practice_files/documents/files/dad.txt diff --git a/ch11-file-input-and-output/practice_files/documents/files/stuff.csv b/ch12-file-input-and-output/practice_files/documents/files/stuff.csv similarity index 100% rename from ch11-file-input-and-output/practice_files/documents/files/stuff.csv rename to ch12-file-input-and-output/practice_files/documents/files/stuff.csv diff --git a/ch11-file-input-and-output/practice_files/documents/image1.png b/ch12-file-input-and-output/practice_files/documents/image1.png similarity index 100% rename from ch11-file-input-and-output/practice_files/documents/image1.png rename to ch12-file-input-and-output/practice_files/documents/image1.png diff --git a/ch11-file-input-and-output/practice_files/documents/more_files/even_more_files/image4.jpg b/ch12-file-input-and-output/practice_files/documents/more_files/even_more_files/image4.jpg similarity index 100% rename from ch11-file-input-and-output/practice_files/documents/more_files/even_more_files/image4.jpg rename to ch12-file-input-and-output/practice_files/documents/more_files/even_more_files/image4.jpg diff --git a/ch11-file-input-and-output/practice_files/documents/more_files/even_more_files/the_answer.txt b/ch12-file-input-and-output/practice_files/documents/more_files/even_more_files/the_answer.txt similarity index 100% rename from ch11-file-input-and-output/practice_files/documents/more_files/even_more_files/the_answer.txt rename to ch12-file-input-and-output/practice_files/documents/more_files/even_more_files/the_answer.txt diff --git a/ch11-file-input-and-output/practice_files/documents/more_files/image2.gif b/ch12-file-input-and-output/practice_files/documents/more_files/image2.gif similarity index 100% rename from ch11-file-input-and-output/practice_files/documents/more_files/image2.gif rename to ch12-file-input-and-output/practice_files/documents/more_files/image2.gif diff --git a/ch11-file-input-and-output/practice_files/documents/more_files/mom.txt b/ch12-file-input-and-output/practice_files/documents/more_files/mom.txt similarity index 100% rename from ch11-file-input-and-output/practice_files/documents/more_files/mom.txt rename to ch12-file-input-and-output/practice_files/documents/more_files/mom.txt diff --git a/ch11-file-input-and-output/practice_files/scores.csv b/ch12-file-input-and-output/practice_files/scores.csv similarity index 100% rename from ch11-file-input-and-output/practice_files/scores.csv rename to ch12-file-input-and-output/practice_files/scores.csv diff --git a/ch13-interact-with-pdf-files/1-extract-text-from-a-pdf.py b/ch14-interact-with-pdf-files/1-extract-text-from-a-pdf.py similarity index 87% rename from ch13-interact-with-pdf-files/1-extract-text-from-a-pdf.py rename to ch14-interact-with-pdf-files/1-extract-text-from-a-pdf.py index 1c44e4e..49e1d76 100644 --- a/ch13-interact-with-pdf-files/1-extract-text-from-a-pdf.py +++ b/ch14-interact-with-pdf-files/1-extract-text-from-a-pdf.py @@ -1,4 +1,4 @@ -# 13.1 - Extract Text From a PDF +# 14.1 - Extract Text From a PDF # Solutions to review exercises @@ -15,11 +15,10 @@ from PyPDF2 import PdfFileReader # To create a PdfFileReader instance, you need to path to the PDF file. -# We'll assume you downloaded the solutions folder and extracted it into -# the home directory on your computer. If this is not the case, you'll +# We'll assume you downloaded the solutions folder and are running this +# program from the solutions folder. If this is not the case, you'll # need to update the path below. -pdf_path = Path.home() / "python-basics-exercises/ch13-interact-with-pdf-files" \ - "/practice_files/zen.pdf" +pdf_path = Path.cwd() / "practice_files" / "zen.pdf" # Now you can create the PdfFileReader instance. Remember that # PdfFileReader objects can only be instantiated with path strings, not diff --git a/ch13-interact-with-pdf-files/2-extract-pages-from-a-pdf.py b/ch14-interact-with-pdf-files/2-extract-pages-from-a-pdf.py similarity index 96% rename from ch13-interact-with-pdf-files/2-extract-pages-from-a-pdf.py rename to ch14-interact-with-pdf-files/2-extract-pages-from-a-pdf.py index b0946cb..fc34b2b 100644 --- a/ch13-interact-with-pdf-files/2-extract-pages-from-a-pdf.py +++ b/ch14-interact-with-pdf-files/2-extract-pages-from-a-pdf.py @@ -1,4 +1,4 @@ -# 13.2 - Extract Pages From a PDF +# 14.2 - Extract Pages From a PDF # Solutions to review exercises # *********** @@ -16,8 +16,7 @@ # downloaded the solutions folder and extracted it into the home # directory on your computer. If this is not the case, you'll need to # update the path below. -pdf_path = Path.home() / "python-basics-exercises/ch13-interact-with-pdf-files" \ - "/practice_files/Pride_and_Prejudice.pdf" +pdf_path = Path.home() / "python-basics-exercises/ch14-interact-with-pdf-files/practice_files/Pride_and_Prejudice.pdf" # Now you can create the PdfFileReader instance. Remember that # PdfFileReader objects can only be instantiated with path strings, not diff --git a/ch13-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py b/ch14-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py similarity index 94% rename from ch13-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py rename to ch14-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py index 4d2cabb..5357574 100644 --- a/ch13-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py +++ b/ch14-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py @@ -1,4 +1,4 @@ -# 13.5 - Challenge: PdfFileSplitter Class +# 14.5 - Challenge: PdfFileSplitter Class # Solution to challenge from pathlib import Path @@ -42,6 +42,6 @@ def write(self, filename): # Split the Pride_and_Prejudice.pdf file into two PDFs, the first # containing the first 150 pages, and the second containing the # remaining pages. -pdf_splitter = PdfFileSplitter("ch13-interact-with-pdf-files/practice_files/Pride_and_Prejudice.pdf") +pdf_splitter = PdfFileSplitter("ch14-interact-with-pdf-files/practice_files/Pride_and_Prejudice.pdf") pdf_splitter.split(breakpoint=150) pdf_splitter.write("pride_split") diff --git a/ch13-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py b/ch14-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py similarity index 89% rename from ch13-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py rename to ch14-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py index e82f700..0753bf6 100644 --- a/ch13-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py +++ b/ch14-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py @@ -1,4 +1,4 @@ -# 13.4 - Concatenating and Merging PDFs +# 14.4 - Concatenating and Merging PDFs # Solutions to review exercises # *********** @@ -15,8 +15,7 @@ from PyPDF2 import PdfFileMerger -BASE_PATH = Path.home() / "python-basics-exercises/" \ - "ch13-interact-with-pdf-files/practice_files" +BASE_PATH = Path.cwd() / "practice_files" pdf_paths = [BASE_PATH / "merge1.pdf", BASE_PATH / "merge2.pdf"] pdf_merger = PdfFileMerger() diff --git a/ch13-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py b/ch14-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py similarity index 92% rename from ch13-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py rename to ch14-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py index 5a52d89..3abe217 100644 --- a/ch13-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py +++ b/ch14-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py @@ -1,4 +1,4 @@ -# 13.5 - Rotating and Cropping PDF pages +# 14.5 - Rotating and Cropping PDF pages # Solutions to review exercises # *********** @@ -15,8 +15,7 @@ from PyPDF2 import PdfFileReader, PdfFileWriter -pdf_path = Path.home() / "python-basics-exercises/" \ - "ch13-interact-with-pdf-files/practice_files/split_and_rotate.pdf" +pdf_path = Path.cwd() / "practice_files" / "split_and_rotate.pdf" pdf_reader = PdfFileReader(str(pdf_path)) pdf_writer = PdfFileWriter() diff --git a/ch13-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py b/ch14-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py similarity index 86% rename from ch13-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py rename to ch14-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py index 889110d..22a365a 100644 --- a/ch13-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py +++ b/ch14-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py @@ -1,4 +1,4 @@ -# 13.6 - Encrypting and Decrypting PDFs +# 14.6 - Encrypting and Decrypting PDFs # Solutions to review exercises # *********** @@ -15,8 +15,7 @@ from PyPDF2 import PdfFileReader, PdfFileWriter -pdf_path = Path.home() / "python-basics-exercises/" \ - "ch13-interact-with-pdf-files/practice_files/top_secret.pdf" +pdf_path = Path.cwd() / "practice_files" / "top_secret.pdf" pdf_reader = PdfFileReader(str(pdf_path)) pdf_writer = PdfFileWriter() diff --git a/ch13-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py b/ch14-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py similarity index 77% rename from ch13-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py rename to ch14-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py index 492d9ea..ded54b2 100644 --- a/ch13-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py +++ b/ch14-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py @@ -1,4 +1,4 @@ -# 13.7 - Challenge: Unscramble a PDF +# 14.7 - Challenge: Unscramble a PDF # Solution to challenge from pathlib import Path @@ -10,8 +10,7 @@ def get_page_text(page): return page.extractText() -pdf_path = Path.home() / "github/realpython/python-basics-exercises/" \ - "ch13-interact-with-pdf-files/practice_files/scrambled.pdf" +pdf_path = Path.cwd() / "practice_files" / "scrambled.pdf" pdf_reader = PdfFileReader(str(pdf_path)) pdf_writer = PdfFileWriter() diff --git a/ch13-interact-with-pdf-files/practice_files/Emperor cover sheet.pdf b/ch14-interact-with-pdf-files/practice_files/Emperor cover sheet.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/Emperor cover sheet.pdf rename to ch14-interact-with-pdf-files/practice_files/Emperor cover sheet.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/Pride_and_Prejudice.pdf b/ch14-interact-with-pdf-files/practice_files/Pride_and_Prejudice.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/Pride_and_Prejudice.pdf rename to ch14-interact-with-pdf-files/practice_files/Pride_and_Prejudice.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/The Emperor.pdf b/ch14-interact-with-pdf-files/practice_files/The Emperor.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/The Emperor.pdf rename to ch14-interact-with-pdf-files/practice_files/The Emperor.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/expense_reports/Expense report 1.pdf b/ch14-interact-with-pdf-files/practice_files/expense_reports/Expense report 1.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/expense_reports/Expense report 1.pdf rename to ch14-interact-with-pdf-files/practice_files/expense_reports/Expense report 1.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/expense_reports/Expense report 2.pdf b/ch14-interact-with-pdf-files/practice_files/expense_reports/Expense report 2.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/expense_reports/Expense report 2.pdf rename to ch14-interact-with-pdf-files/practice_files/expense_reports/Expense report 2.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/expense_reports/Expense report 3.pdf b/ch14-interact-with-pdf-files/practice_files/expense_reports/Expense report 3.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/expense_reports/Expense report 3.pdf rename to ch14-interact-with-pdf-files/practice_files/expense_reports/Expense report 3.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/half_and_half.pdf b/ch14-interact-with-pdf-files/practice_files/half_and_half.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/half_and_half.pdf rename to ch14-interact-with-pdf-files/practice_files/half_and_half.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/merge1.pdf b/ch14-interact-with-pdf-files/practice_files/merge1.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/merge1.pdf rename to ch14-interact-with-pdf-files/practice_files/merge1.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/merge2.pdf b/ch14-interact-with-pdf-files/practice_files/merge2.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/merge2.pdf rename to ch14-interact-with-pdf-files/practice_files/merge2.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/merge3.pdf b/ch14-interact-with-pdf-files/practice_files/merge3.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/merge3.pdf rename to ch14-interact-with-pdf-files/practice_files/merge3.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/newsletter.pdf b/ch14-interact-with-pdf-files/practice_files/newsletter.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/newsletter.pdf rename to ch14-interact-with-pdf-files/practice_files/newsletter.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/quarterly_report/full_report.pdf b/ch14-interact-with-pdf-files/practice_files/quarterly_report/full_report.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/quarterly_report/full_report.pdf rename to ch14-interact-with-pdf-files/practice_files/quarterly_report/full_report.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/quarterly_report/report.pdf b/ch14-interact-with-pdf-files/practice_files/quarterly_report/report.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/quarterly_report/report.pdf rename to ch14-interact-with-pdf-files/practice_files/quarterly_report/report.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/quarterly_report/toc.pdf b/ch14-interact-with-pdf-files/practice_files/quarterly_report/toc.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/quarterly_report/toc.pdf rename to ch14-interact-with-pdf-files/practice_files/quarterly_report/toc.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/scrambled.pdf b/ch14-interact-with-pdf-files/practice_files/scrambled.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/scrambled.pdf rename to ch14-interact-with-pdf-files/practice_files/scrambled.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/split_and_rotate.pdf b/ch14-interact-with-pdf-files/practice_files/split_and_rotate.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/split_and_rotate.pdf rename to ch14-interact-with-pdf-files/practice_files/split_and_rotate.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/top_secret.pdf b/ch14-interact-with-pdf-files/practice_files/top_secret.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/top_secret.pdf rename to ch14-interact-with-pdf-files/practice_files/top_secret.pdf diff --git a/ch13-interact-with-pdf-files/practice_files/ugly.pdf b/ch14-interact-with-pdf-files/practice_files/ugly.pdf similarity index 100% rename from ch13-interact-with-pdf-files/practice_files/ugly.pdf rename to ch14-interact-with-pdf-files/practice_files/ugly.pdf diff --git a/ch14-interact-with-pdf-files/practice_files/zen.pdf b/ch14-interact-with-pdf-files/practice_files/zen.pdf new file mode 100644 index 0000000..839484f Binary files /dev/null and b/ch14-interact-with-pdf-files/practice_files/zen.pdf differ diff --git a/ch14-sql-database-connections/1-use-sqlite.py b/ch14-sql-database-connections/1-use-sqlite.py deleted file mode 100644 index 483d0e9..0000000 --- a/ch14-sql-database-connections/1-use-sqlite.py +++ /dev/null @@ -1,33 +0,0 @@ -# 14.1 - Use SQLite -# Solutions to review exercises - -import sqlite3 - -# Create a temporary database connection in RAM -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), - ("Korben Dallas", "Meat Popsicle", 100), - ("Ak'not", "Mangalore", -5), - ) - 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(): - print(row) diff --git a/ch15-sql-database-connections/1-use-sqlite.py b/ch15-sql-database-connections/1-use-sqlite.py new file mode 100644 index 0000000..d5cfc09 --- /dev/null +++ b/ch15-sql-database-connections/1-use-sqlite.py @@ -0,0 +1,33 @@ +# 15.1 - Use SQLite +# Solutions to review exercises + +import sqlite3 + +# Create a temporary database connection in RAM +with sqlite3.connect(":memory:") as connection: + c = connection.cursor() + + # Exercise 1 + # Create a "Roster" table with Name, Species and Age fields + c.execute("CREATE TABLE Roster(Name TEXT, Species TEXT, Age INT)") + + # Exercise 2 + # Add some data into the database + roster_data = ( + ("Benjamin Sisko", "Human", 40), + ("Jadzia Dax", "Trill", 300), + ("Kira Nerys", "Bajoran", 29), + ) + c.executemany("INSERT INTO Roster VALUES(?, ?, ?)", roster_data) + + # Exercise 3 + # Update the Name of Jadzia Dax to "Ezri Dax" + c.execute( + "UPDATE Roster SET Name=? WHERE Name=?", ("Ezri Dax", "Jadzia Dax") + ) + + # Exercise 4 + # Display the names and ages of everyone classified as Bajoran + c.execute("SELECT Name, Age FROM Roster WHERE Species = 'Bajoran'") + for row in c.fetchall(): + print(row) diff --git a/ch15-interacting-with-the-web/1-scrape-and-parse-text-from-websites.py b/ch16-interacting-with-the-web/1-scrape-and-parse-text-from-websites.py similarity index 95% rename from ch15-interacting-with-the-web/1-scrape-and-parse-text-from-websites.py rename to ch16-interacting-with-the-web/1-scrape-and-parse-text-from-websites.py index 7f33108..851515d 100644 --- a/ch15-interacting-with-the-web/1-scrape-and-parse-text-from-websites.py +++ b/ch16-interacting-with-the-web/1-scrape-and-parse-text-from-websites.py @@ -1,4 +1,4 @@ -# 15.1 - Scrape and Parse Text From Websites +# 16.1 - Scrape and Parse Text From Websites # Solutions to review exercises from urllib.request import urlopen diff --git a/ch15-interacting-with-the-web/2-use-an-html-parser-to-scrape-websites.py b/ch16-interacting-with-the-web/2-use-an-html-parser-to-scrape-websites.py similarity index 95% rename from ch15-interacting-with-the-web/2-use-an-html-parser-to-scrape-websites.py rename to ch16-interacting-with-the-web/2-use-an-html-parser-to-scrape-websites.py index 8b70919..4781c1f 100644 --- a/ch15-interacting-with-the-web/2-use-an-html-parser-to-scrape-websites.py +++ b/ch16-interacting-with-the-web/2-use-an-html-parser-to-scrape-websites.py @@ -1,4 +1,4 @@ -# 15.2 - Use an HTML Parser to Scrape Websites +# 16.2 - Use an HTML Parser to Scrape Websites # Solutions to review exercises # Make sure BeautifulSoup is installed first with: diff --git a/ch15-interacting-with-the-web/3-interact-with-html-forms.py b/ch16-interacting-with-the-web/3-interact-with-html-forms.py similarity index 97% rename from ch15-interacting-with-the-web/3-interact-with-html-forms.py rename to ch16-interacting-with-the-web/3-interact-with-html-forms.py index c1741e3..26eaf2a 100644 --- a/ch15-interacting-with-the-web/3-interact-with-html-forms.py +++ b/ch16-interacting-with-the-web/3-interact-with-html-forms.py @@ -1,4 +1,4 @@ -# 15.3 - Interact with HTML Forms +# 16.3 - Interact with HTML Forms # Solutions to review exercises # Make sure BeautifulSoup is installed first with: diff --git a/ch15-interacting-with-the-web/4-interact-with-websites-in-realtime.py b/ch16-interacting-with-the-web/4-interact-with-websites-in-realtime.py similarity index 95% rename from ch15-interacting-with-the-web/4-interact-with-websites-in-realtime.py rename to ch16-interacting-with-the-web/4-interact-with-websites-in-realtime.py index 60ac5ee..90767c1 100644 --- a/ch15-interacting-with-the-web/4-interact-with-websites-in-realtime.py +++ b/ch16-interacting-with-the-web/4-interact-with-websites-in-realtime.py @@ -1,4 +1,4 @@ -# 15.4 - Interact With Websites in Real-Time +# 16.4 - Interact With Websites in Real-Time # Solutions to review exercise # Make sure BeautifulSoup is installed first with: diff --git a/ch16-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py b/ch17-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py similarity index 90% rename from ch16-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py rename to ch17-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py index 839fc31..20a3307 100644 --- a/ch16-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py +++ b/ch17-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py @@ -1,4 +1,4 @@ -# 16.2 - Use matplotlib for Plotting Graphs +# 17.2 - Use matplotlib for Plotting Graphs # Solution to review exercise #2 # Setup @@ -17,7 +17,7 @@ # Exercise 3 # Square every entry and save in a new matrix -second_matrix = first_matrix ** 2 +second_matrix = first_matrix**2 # Exercise 4 # Put first_matrix on top of second_matrix diff --git a/ch16-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py b/ch17-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py similarity index 92% rename from ch16-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py rename to ch17-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py index 92f778b..3afa8eb 100644 --- a/ch16-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py +++ b/ch17-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py @@ -1,4 +1,4 @@ -# 16.3 - Use matplotlib for Plotting Graphs +# 17.3 - Use matplotlib for Plotting Graphs # Solution to review exercise #2 # Graph pirates versus global warming @@ -8,8 +8,7 @@ import os # Change `path` to actual path on your system -path = "C:/Real Python/python-basics-exercises/ch16-scientific-computing-and-graphing/\ -practice_files" +path = "C:/Real Python/python-basics-exercises/ch16-scientific-computing-and-graphing/practice_files" years = [] temperatures = [] diff --git a/ch16-scientific-computing-and-graphing/practice_files/pirates.csv b/ch17-scientific-computing-and-graphing/practice_files/pirates.csv similarity index 100% rename from ch16-scientific-computing-and-graphing/practice_files/pirates.csv rename to ch17-scientific-computing-and-graphing/practice_files/pirates.csv diff --git a/ch17-graphical-user-interfaces/1-add-gui-elements-with-easygui.py b/ch18-graphical-user-interfaces/1-add-gui-elements-with-easygui.py similarity index 82% rename from ch17-graphical-user-interfaces/1-add-gui-elements-with-easygui.py rename to ch18-graphical-user-interfaces/1-add-gui-elements-with-easygui.py index 3fe3780..bd09fb9 100644 --- a/ch17-graphical-user-interfaces/1-add-gui-elements-with-easygui.py +++ b/ch18-graphical-user-interfaces/1-add-gui-elements-with-easygui.py @@ -1,4 +1,4 @@ -# 17.1 - Add GUI Elements with EasyGUI +# 18.1 - Add GUI Elements with EasyGUI # Review Exercises import easygui as gui diff --git a/ch17-graphical-user-interfaces/10-challenge-return-of-the-poet.py b/ch18-graphical-user-interfaces/10-challenge-return-of-the-poet.py similarity index 99% rename from ch17-graphical-user-interfaces/10-challenge-return-of-the-poet.py rename to ch18-graphical-user-interfaces/10-challenge-return-of-the-poet.py index 5373168..b7af37f 100644 --- a/ch17-graphical-user-interfaces/10-challenge-return-of-the-poet.py +++ b/ch18-graphical-user-interfaces/10-challenge-return-of-the-poet.py @@ -1,4 +1,4 @@ -# 17.10 - Challenge: Return of the Poet +# 18.10 - Challenge: Return of the Poet # Solution to challenge # Please note that there are many ways to solve this challenge. The code diff --git a/ch17-graphical-user-interfaces/2-example-app-pdf-page-rotator.py b/ch18-graphical-user-interfaces/2-example-app-pdf-page-rotator.py similarity index 98% rename from ch17-graphical-user-interfaces/2-example-app-pdf-page-rotator.py rename to ch18-graphical-user-interfaces/2-example-app-pdf-page-rotator.py index ea097f6..3399e32 100644 --- a/ch17-graphical-user-interfaces/2-example-app-pdf-page-rotator.py +++ b/ch18-graphical-user-interfaces/2-example-app-pdf-page-rotator.py @@ -1,4 +1,4 @@ -# 17.2 - Example App: PDF Page Rotator +# 18.2 - Example App: PDF Page Rotator # Review Exercise #1 import easygui as gui diff --git a/ch17-graphical-user-interfaces/3-challenge-use-gui-elements-to-help-a-user-modify-files.py b/ch18-graphical-user-interfaces/3-challenge-use-gui-elements-to-help-a-user-modify-files.py similarity index 98% rename from ch17-graphical-user-interfaces/3-challenge-use-gui-elements-to-help-a-user-modify-files.py rename to ch18-graphical-user-interfaces/3-challenge-use-gui-elements-to-help-a-user-modify-files.py index 0a76cfc..128dd6a 100644 --- a/ch17-graphical-user-interfaces/3-challenge-use-gui-elements-to-help-a-user-modify-files.py +++ b/ch18-graphical-user-interfaces/3-challenge-use-gui-elements-to-help-a-user-modify-files.py @@ -1,4 +1,4 @@ -# 17.3 - Challenge: Use GUI Elements to Help a User Modify Files +# 18.3 - Challenge: Use GUI Elements to Help a User Modify Files # Solution to challenge # save part of a PDF based on a user-supplied page range using a GUI diff --git a/ch17-graphical-user-interfaces/4-introduction-to-tkinter.py b/ch18-graphical-user-interfaces/4-introduction-to-tkinter.py similarity index 91% rename from ch17-graphical-user-interfaces/4-introduction-to-tkinter.py rename to ch18-graphical-user-interfaces/4-introduction-to-tkinter.py index 3027770..8f612c8 100644 --- a/ch17-graphical-user-interfaces/4-introduction-to-tkinter.py +++ b/ch18-graphical-user-interfaces/4-introduction-to-tkinter.py @@ -1,4 +1,4 @@ -# 17.4 - Introduction to Tkinter +# 18.4 - Introduction to Tkinter # Review exercises import tkinter as tk diff --git a/ch17-graphical-user-interfaces/5-working-with-widgets.py b/ch18-graphical-user-interfaces/5-working-with-widgets.py similarity index 93% rename from ch17-graphical-user-interfaces/5-working-with-widgets.py rename to ch18-graphical-user-interfaces/5-working-with-widgets.py index ca98a0c..3074995 100644 --- a/ch17-graphical-user-interfaces/5-working-with-widgets.py +++ b/ch18-graphical-user-interfaces/5-working-with-widgets.py @@ -1,4 +1,4 @@ -# 17.4 - Introduction to Tkinter +# 18.4 - Introduction to Tkinter # Review exercises import tkinter as tk diff --git a/ch17-graphical-user-interfaces/6-control-layout-with-geometry-managers.py b/ch18-graphical-user-interfaces/6-control-layout-with-geometry-managers.py similarity index 98% rename from ch17-graphical-user-interfaces/6-control-layout-with-geometry-managers.py rename to ch18-graphical-user-interfaces/6-control-layout-with-geometry-managers.py index 339c992..5c2869a 100644 --- a/ch17-graphical-user-interfaces/6-control-layout-with-geometry-managers.py +++ b/ch18-graphical-user-interfaces/6-control-layout-with-geometry-managers.py @@ -1,4 +1,4 @@ -# 17.6 - Control Layout With Geometry Managers +# 18.6 - Control Layout With Geometry Managers # Review Exercise #2 # NOTE: The first exercise in this section is instructional and does diff --git a/ch17-graphical-user-interfaces/7-make-your-applications-interactive.py b/ch18-graphical-user-interfaces/7-make-your-applications-interactive.py similarity index 94% rename from ch17-graphical-user-interfaces/7-make-your-applications-interactive.py rename to ch18-graphical-user-interfaces/7-make-your-applications-interactive.py index f9e883f..6f2a39a 100644 --- a/ch17-graphical-user-interfaces/7-make-your-applications-interactive.py +++ b/ch18-graphical-user-interfaces/7-make-your-applications-interactive.py @@ -1,4 +1,4 @@ -# 17.7 - Make Your Applications Interactive +# 18.7 - Make Your Applications Interactive # Review Exercises