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 a531e9e..06929d4 100755 --- a/README.md +++ b/README.md @@ -34,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/6-working-with-strings-and-numbers.py b/ch04-strings-and-string-methods/6-working-with-strings-and-numbers.py index 313621e..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 @@ -33,4 +33,4 @@ 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/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 5d1e075..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 @@ -16,9 +16,9 @@ def single_trial(): - """Simulate repeatedly a coing until both heads and tails are seen.""" + """Simulate repeatedly flipping a coin until both heads and tails are seen.""" # This function uses random.randint() to simulate a single coin toss. - # randing(0, 1) randomly returns 0 or 1 with equal probability. We can + # randint(0, 1) randomly returns 0 or 1 with equal probability. We can # use 0 to represent heads and 1 to represent tails. # Flip the coin the first time 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/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/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 06a0cb4..36efe49 100644 --- a/ch10-primer-on-oop/3-inherit-from-other-classes.py +++ b/ch10-primer-on-oop/3-inherit-from-other-classes.py @@ -41,4 +41,7 @@ def __init__(self, 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/ch12-file-input-and-output/3-common-file-system-operations.py b/ch12-file-input-and-output/3-common-file-system-operations.py index 73c506b..eaf8042 100644 --- a/ch12-file-input-and-output/3-common-file-system-operations.py +++ b/ch12-file-input-and-output/3-common-file-system-operations.py @@ -29,6 +29,7 @@ file1.unlink() -# # Exercise 5 +# Exercise 5 import shutil + shutil.rmtree(new_dir) diff --git a/ch12-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 index 5affd34..b39266c 100644 --- a/ch12-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 @@ -4,13 +4,7 @@ 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/ch12-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 index f0e1fa5..f9539f8 100644 --- a/ch12-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 @@ -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/ch14-interact-with-pdf-files/1-extract-text-from-a-pdf.py b/ch14-interact-with-pdf-files/1-extract-text-from-a-pdf.py index bd56625..49e1d76 100644 --- a/ch14-interact-with-pdf-files/1-extract-text-from-a-pdf.py +++ b/ch14-interact-with-pdf-files/1-extract-text-from-a-pdf.py @@ -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/ch14-interact-with-pdf-files/2-extract-pages-from-a-pdf.py b/ch14-interact-with-pdf-files/2-extract-pages-from-a-pdf.py index a39d947..fc34b2b 100644 --- a/ch14-interact-with-pdf-files/2-extract-pages-from-a-pdf.py +++ b/ch14-interact-with-pdf-files/2-extract-pages-from-a-pdf.py @@ -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/ch14-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py b/ch14-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py index b137dc3..5357574 100644 --- a/ch14-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py +++ b/ch14-interact-with-pdf-files/3-challenge-PdfFileSplitter-class.py @@ -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/ch14-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py b/ch14-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py index eef0d12..0753bf6 100644 --- a/ch14-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py +++ b/ch14-interact-with-pdf-files/4-concatenating-and-merging-pdfs.py @@ -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/ch14-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py b/ch14-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py index a3ceefd..3abe217 100644 --- a/ch14-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py +++ b/ch14-interact-with-pdf-files/5-rotating-and-cropping-pdf-pages.py @@ -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/ch14-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py b/ch14-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py index 98bf0e3..22a365a 100644 --- a/ch14-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py +++ b/ch14-interact-with-pdf-files/6-encrypting-and-decrypting-pdfs.py @@ -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/ch14-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py b/ch14-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py index 4e5eeea..ded54b2 100644 --- a/ch14-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py +++ b/ch14-interact-with-pdf-files/7-challenge-unscramble-a-pdf.py @@ -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/ch15-sql-database-connections/1-use-sqlite.py b/ch15-sql-database-connections/1-use-sqlite.py index 3573991..d5cfc09 100644 --- a/ch15-sql-database-connections/1-use-sqlite.py +++ b/ch15-sql-database-connections/1-use-sqlite.py @@ -8,26 +8,26 @@ 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)") + # 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 = ( - ("Jean-Baptiste Zorg", "Human", 122), - ("Korben Dallas", "Meat Popsicle", 100), - ("Ak'not", "Mangalore", -5), + ("Benjamin Sisko", "Human", 40), + ("Jadzia Dax", "Trill", 300), + ("Kira Nerys", "Bajoran", 29), ) c.executemany("INSERT INTO Roster VALUES(?, ?, ?)", roster_data) # Exercise 3 - # Update the Species of Korben Dallas to "Human" + # Update the Name of Jadzia Dax to "Ezri Dax" c.execute( - "UPDATE Roster SET Species=? WHERE Name=?", ("Human", "Korben Dallas") + "UPDATE Roster SET Name=? WHERE Name=?", ("Ezri Dax", "Jadzia Dax") ) # Exercise 4 - # Display the names and IQs of everyone classified as Human - c.execute("SELECT Name, IQ FROM Roster WHERE Species = 'Human'") + # 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/ch17-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py b/ch17-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py index 28e0555..20a3307 100644 --- a/ch17-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py +++ b/ch17-scientific-computing-and-graphing/1-use-numpy-for-matrix-manipulation.py @@ -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/ch17-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py b/ch17-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py index 63a805b..3afa8eb 100644 --- a/ch17-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py +++ b/ch17-scientific-computing-and-graphing/2-use-matplotlib-for-plotting-graphs.py @@ -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 = []