Lab 5¶
Submission instructions¶
- Download the notebook from https://geohey.gishub.org/labs/lab5
- Complete the lab questions
- Restart Kernel and Run All Cells
- Upload the notebook to your GitHub repository
- Make sure the notebook has an
Open In Colab
badge. Click on the badge to make sure your notebook can be opened in Colab. - Submit the link to the notebook on your GitHub repository to Canvas
Question 1¶
Person: Use a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as first_name, last_name, age, and city. Print each piece of information stored in your dictionary.
person_info = {
"first_name": "Morgan",
"last_name": "Freeman",
"age": 30,
"city": "New York"
}
print( person_info["first_name"])
print( person_info["last_name"])
print( person_info["age"])
print( person_info["city"])
Morgan Freeman 30 New York
Question 2¶
Favorite Numbers: Use a dictionary to store people’s favorite numbers. Think of five names, and use them as keys in your dictionary. Think of a favorite number for each person, and store each as a value in your dictionary. Print each person’s name and their favorite number. For even more fun, poll a few friends and get some actual data for your program.
favorite_numbers = {
"Alice": 7,
"Bob": 12,
"Charlie": 5,
"David": 9,
"Emily": 3
}
for name, number in favorite_numbers.items():
print(f"{name}'s favorite number is {number}.")
Alice's favorite number is 7. Bob's favorite number is 12. Charlie's favorite number is 5. David's favorite number is 9. Emily's favorite number is 3.
Question 3¶
Glossary: A Python dictionary can be used to model an actual dictionary. However, to avoid confusion, let’s call it a glossary.
- Think of five programming words you’ve learned about in the previous chapters. Use these words as the keys in your glossary, and store their meanings as values.
- Print each word and its meaning as neatly formatted output. You might print the word followed by a colon and then its meaning, or print the word on one line and then print its meaning indented on a second line. Use the newline character (\n) to insert a blank line between each word-meaning pair in your output.
glossary = {
"variable": "A placeholder for storing data value.",
"comment": "A comment allows you to wrote notes in English in your parameters.",
"function": "A block of code that only runs when it is called.",
"list": "A list is a collection of items in a particular order",
"loop": "A programming construct that repeats a block of code until a specified condition is met.",
"dictionary": "A collection which is unordered, changeable, and indexed. No duplicate members."
}
for word, meaning in glossary.items():
print(f"{word}: {meaning}\n")
variable: A placeholder for storing data value. comment: A comment allows you to wrote notes in English in your parameters. function: A block of code that only runs when it is called. list: A list is a collection of items in a particular order loop: A programming construct that repeats a block of code until a specified condition is met. dictionary: A collection which is unordered, changeable, and indexed. No duplicate members.
Question 4¶
Glossary 2: Now that you know how to loop through a dictionary, clean up the code from Question 3 by replacing your series of print() calls with a loop that runs through the dictionary’s keys and values. When you’re sure that your loop works, add five more Python terms to your glossary. When you run your program again, these new words and meanings should automatically be included in the output.
glossary = {
"variable": "A placeholder for storing data value.",
"comment": "A comment allows you to write notes in English in your parameters.",
"function": "A block of code that only runs when it is called.",
"list": "A list is a collection of items in a particular order.",
"loop": "A programming construct that repeats a block of code until a specified condition is met.",
"dictionary": "A collection which is unordered, changeable, and indexed. No duplicate members.",
"module": "A file containing Python definitions and statements.",
"string": "A sequence of characters, used to represent text.",
"tuple": "A collection which is ordered and unchangeable. Allows duplicate members.",
"conditional statements": "Allow you to check any condition of interest"
}
for word, meaning in glossary.items():
print(f"{word}:\n {meaning}\n")
variable: A placeholder for storing data value. comment: A comment allows you to write notes in English in your parameters. function: A block of code that only runs when it is called. list: A list is a collection of items in a particular order. loop: A programming construct that repeats a block of code until a specified condition is met. dictionary: A collection which is unordered, changeable, and indexed. No duplicate members. module: A file containing Python definitions and statements. string: A sequence of characters, used to represent text. tuple: A collection which is ordered and unchangeable. Allows duplicate members. conditional statements: Allow you to check any condition of interest
Question 5¶
Rivers: Make a dictionary containing three major rivers and the country each river runs through. One key-value pair might be 'nile': 'egypt'.
- Use a loop to print a sentence about each river, such as The Nile runs through Egypt.
- Use a loop to print the name of each river included in the dictionary.
- Use a loop to print the name of each country included in the dictionary.
major_rivers = {
"Nile": "Egypt",
"Amazon": "Brazil",
"Mississippi": "United States"
}
print("Sentences about each river:")
for river, country in major_rivers.items():
print(f"The {river} runs through {country}.")
print("\nNames of rivers:")
for river in major_rivers:
print(river)
print("\nNames of countries:")
for country in major_rivers.values():
print(country)
Sentences about each river: The Nile runs through Egypt. The Amazon runs through Brazil. The Mississippi runs through United States. Names of rivers: Nile Amazon Mississippi Names of countries: Egypt Brazil United States
Question 6¶
Cities: Make a dictionary called cities
. Use the names of three cities as keys in your dictionary. Create a dictionary of information about each city and include the country that the city is in, its approximate population, and one fact about that city. The keys for each city’s dictionary should be something like country
, population
, and fact
. Print the name of each city and all of the information you have stored about it.
cities = {
"Tokyo": {
"country": "Japan",
"population": "37.4 million",
"fact": "Tokyo is the largest metropolitan area in the world."
},
"New York": {
"country": "United States",
"population": "8.4 million",
"fact": "New York City is known as the city that never sleeps."
},
"London": {
"country": "United Kingdom",
"population": "8.9 million",
"fact": "London is home to the oldest pub in the world."
}
}
for city, info in cities.items():
print(f"{city}:")
print(f"Country: {info['country']}")
print(f"Population: {info['population']}")
print(f"Fact: {info['fact']}\n")
Tokyo: Country: Japan Population: 37.4 million Fact: Tokyo is the largest metropolitan area in the world. New York: Country: United States Population: 8.4 million Fact: New York City is known as the city that never sleeps. London: Country: United Kingdom Population: 8.9 million Fact: London is home to the oldest pub in the world.
Question 7¶
Rental Car: Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as “Let me see if I can find you a Subaru.”
rental_car = input("What kind of rental car would you like? ")
print(f"Let me see if I can find you a {rental_car}.")
Let me see if I can find you a kia.
Question 8¶
Restaurant Seating: Write a program that asks the user how many people are in their dinner group. If the answer is more than eight, print a message saying they’ll have to wait for a table. Otherwise, report that their table is ready.
dinner_group = input("How many people are in your dinner group? ")
dinner_group = int(dinner_group)
if dinner_group > 8:
print ("Sorry you will have to wait for a table.")
else:
print("Your table is ready.")
Sorry you will have to wait for a table.
Question 9¶
Multiples of Ten: Ask the user for a number, and then report whether the number is a multiple of 10 or not.
number = input("Please enter a number: ")
number = int(number)
if number % 10 == 0:
print(f"{number} is a multiple of 10.")
else:
print(f"{number} is not a multiple of 10.")
263 is not a multiple of 10.
Question 10¶
Pizza Toppings: Write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value. As they enter each topping, print a message saying you’ll add that topping to their pizza.
pizza_toppings = []
while True:
topping = input("Enter a pizza topping (enter 'quit' to finish): ")
if topping.lower() == 'quit':
break
pizza_toppings.append(topping)
print(f"Adding {topping} to your pizza.")
print("\nYour pizza will have the following toppings:")
for topping in pizza_toppings:
print(topping)
Adding pepperoni to your pizza. Adding mushroom to your pizza. Your pizza will have the following toppings: pepperoni mushroom
Question 11¶
Message: Write a function called display_message()
that prints one sentence telling everyone what you are learning about in this chapter. Call the function, and make sure the message displays correctly.
def display_message():
message = "In this chapter, we are learning about functions in Python."
print(message)
display_message()
In this chapter, we are learning about functions in Python.
Question 12¶
Favorite Book: Write a function called favorite_book()
that accepts one parameter, title. The function should print a message, such as One of my favorite books is Alice in Wonderland
. Call the function, making sure to include a book title as an argument in the function call.
def favorite_book(title):
print (f"One of my favorite books is {title}")
favorite_book("Invisible Man")
One of my favorite books is Invisible Man
Question 13¶
T-Shirt: Write a function called make_shirt()
that accepts a size and the text of a message that should be printed on the shirt. The function should print a sentence summarizing the size of the shirt and the message printed on it.
Call the function once using positional arguments to make a shirt. Call the function a second time using keyword arguments.
def make_shirt(size, message):
"""Prints a summary of the shirt size and message."""
print(f"Shirt size: {size.lower()}, Message: '{message}'")
make_shirt("medium", "Dr.Wu's Class,")
make_shirt("large", "Is the best!")
Shirt size: medium, Message: 'Dr.Wu's Class,' Shirt size: large, Message: 'Is the best!'
Question 14¶
Large Shirts: Modify the make_shirt()
function so that shirts are large by default with a message that reads I love Python. Make a large shirt and a medium shirt with the default message, and a shirt of any size with a different message.
def make_shirt(size="large", message="I love Python"):
print(f"Shirt size: {size.title()}, Message: '{message}'")
make_shirt()
make_shirt("medium")
make_shirt("small", "Keep calm and code on!")
Shirt size: Large, Message: 'I love Python' Shirt size: Medium, Message: 'I love Python' Shirt size: Small, Message: 'Keep calm and code on!'
Question 15¶
Cities: Write a function called describe_city()
that accepts the name of a city and its country. The function should print a simple sentence, such as Reykjavik is in Iceland
. Give the parameter for the country a default value. Call your function for three different cities, at least one of which is not in the default country.
def describe_city(city, country="Iceland"):
print(f"{city.title()} is in {country.title()}.")
describe_city("Tokyo", "Japan")
describe_city("Reykjavik")
describe_city("Toronto", "Canada")
Tokyo is in Japan. Reykjavik is in Iceland. Toronto is in Canada.
Question 16¶
City Names: Write a function called city_country()
that takes in the name of a city and its country. The function should return a string formatted like this:
Santiago, Chile
Call your function with at least three city-country pairs, and print the values that are returned.
def city_country(city, country):
return f"{city.title()}, {country.title()}"
print(city_country("london", "england"))
print(city_country("cairo", "egypt"))
print(city_country("new york city", "usa"))
London, England Cairo, Egypt New York City, Usa
Question 17¶
Album: Write a function called make_album()
that builds a dictionary describing a music album. The function should take in an artist name and an album title, and it should return a dictionary containing these two pieces of information. Use the function to make three dictionaries representing different albums. Print each return value to show that the dictionaries are storing the album information correctly.
Use None to add an optional parameter to make_album() that allows you to store the number of songs on an album. If the calling line includes a value for the number of songs, add that value to the album’s dictionary. Make at least one new function call that includes the number of songs on an album.
def make_album(artist_name, album_title, number_of_songs=None):
album = {'artist': artist_name.title(), 'album': album_title.title()}
if number_of_songs:
album['songs'] = number_of_songs
return album
album1 = make_album("grateful dead", "american beauty")
album2 = make_album("the beatles", "abbey road")
album3 = make_album("kendrick lamar", "to pimp a butterfly", 16)
print(album1)
print(album2)
print(album3)
{'artist': 'Grateful Dead', 'album': 'American Beauty'} {'artist': 'The Beatles', 'album': 'Abbey Road'} {'artist': 'Kendrick Lamar', 'album': 'To Pimp A Butterfly', 'songs': 16}
Question 18¶
User Albums: Start with your program from Question 17. Write a while
loop that allows users to enter an album’s artist and title. Once you have that information, call make_album()
with the user’s input and print the dictionary that’s created. Be sure to include a quit value in the while
loop.
def make_album(artist_name, album_title, number_of_songs=None):
album = {'artist': artist_name.title(), 'album': album_title.title()}
if number_of_songs:
album['songs'] = number_of_songs
return album
while True:
print("\nEnter 'q' to quit.")
artist_name = input("Artist name: ")
if artist_name.lower() == 'q':
break
album_title = input("Album title: ")
number_of_songs = input("Number of songs (optional): ")
if number_of_songs.isdigit():
number_of_songs = int(number_of_songs)
else:
number_of_songs = None
album = make_album(artist_name, album_title, number_of_songs)
print(album)
Enter 'q' to quit. {'artist': 'Grateful Dead', 'album': 'Workingmans Dead', 'songs': 12} Enter 'q' to quit. {'artist': 'Beatles', 'album': 'White Revolver', 'songs': 13} Enter 'q' to quit. {'artist': 'Rolling Stones', 'album': 'Paint It Black', 'songs': 14} Enter 'q' to quit.
Question 19¶
Messages: Make a list containing a series of short text messages. Pass the list to a function called show_messages()
, which prints each text message.
def show_messages(messages):
for message in messages:
print(message)
messages = ["Whats up!", "Whats going on?", "See you later, alligator!"]
show_messages (messages)
Whats up! Whats going on? See you later, alligator!
Question 20¶
Sending Messages: Start with a copy of your program from Question 19. Write a function called send_messages()
that prints each text message and moves each message to a new list called sent_messages
as it’s printed. After calling the function, print both of your lists to make sure the messages were moved correctly.
def show_messages(messages):
for message in messages:
print(message)
def send_messages(messages, sent_messages):
while messages:
current_message = messages.pop(0)
print("Sending message.", current_message)
sent_messages.append(current_message)
messages = ["Whats up!", "Whats going on?", "See you later, alligator!"]
sent_messages = []
send_messages(messages, sent_messages)
print("\nOriginal messages:")
show_messages(messages)
print("\nSent messages:")
show_messages(sent_messages)
Sending message. Whats up! Sending message. Whats going on? Sending message. See you later, alligator! Original messages: Sent messages: Whats up! Whats going on? See you later, alligator!
Question 21¶
Learning Python: Open a blank file in your text editor and write a few lines summarizing what you’ve learned about Python so far. Start each line with the phrase In Python you can. . .. Save the file as learning_python.txt in the same directory as your exercises from this chapter. Write a program that reads the file and prints what you wrote three times. Print the contents once by reading in the entire file, once by looping over the file object, and once by storing the lines in a list and then working with them outside the with block.
print(" Reading the file by reading in the entire file ")
with open('learning_python.txt', 'r') as file:
contents = file.read()
print(contents)
Reading the file by reading in the entire file In python you can create loops to loop through a dictionary.\ In python you can create while loops for conditional if and statements until the code is told to stop executing.\ In python you can create lists that are ordered and undordered. \ In python you can create different kinds of functions for your packages.
print("\n Reading the file by looping over the file object ")
with open('learning_python.txt', 'r') as file:
for line in file:
print(line.strip())
Reading the file by looping over the file object In python you can create loops to loop through a dictionary.\ In python you can create while loops for conditional if and statements until the code is told to stop executing.\ In python you can create lists that are ordered and undordered. \ In python you can create different kinds of functions for your packages.
print("\n Reading the file by storing lines in a list and working with them outside the with block ")
lines = []
with open('learning_python.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
Reading the file by storing lines in a list and working with them outside the with block In python you can create loops to loop through a dictionary.\ In python you can create while loops for conditional if and statements until the code is told to stop executing.\ In python you can create lists that are ordered and undordered. \ In python you can create different kinds of functions for your packages.
Question 22¶
Learning C: You can use the replace() method to replace any word in a string with a different word. Here’s a quick example showing how to replace 'dog' with 'cat' in a sentence:
message = "I really like dogs."
message.replace('dog', 'cat')
'I really like cats.'
Read in each line from the file you just created, learning_python.txt, and replace the word Python with the name of another language, such as C. Print each modified line to the screen.
with open('learning_python.txt', 'r') as file:
for line in file:
modified_line = line.replace('python', 'C')
print(modified_line.strip())
In C you can create loops to loop through a dictionary.\ In C you can create while loops for conditional if and statements until the code is told to stop executing.\ In C you can create lists that are ordered and undordered. \ In C you can create different kinds of functions for your packages.
Question 23¶
Guest: Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt.
name = input("Please enter your name: ")
with open('guest.txt', 'w') as file:
file.write(name)
print("Your name has been written to guest list")
Your name has been written to guest list
Question 24¶
Guest Book: Write a while loop that prompts users for their name. When they enter their name, print a greeting to the screen and add a line recording their visit in a file called guest_book.txt. Make sure each entry appears on a new line in the file.
with open('guest_book.txt', 'a') as file:
while True:
name = input("Please enter your name (enter 'q' to quit): ")
if name.lower() == 'q':
break
print(f"Welcome, {name}!")
file.write(name +'\n')
print("Thank you for visiting!")
Welcome, will sturgill! Thank you for visiting!
Question 25¶
Programming Poll: Write a while loop that asks people why they like programming. Each time someone enters a reason, add their reason to a file that stores all the responses.
with open('programming.txt', 'a') as file:
while True:
reason = input("Why do you like programming? (Enter 'q' to quit): ")
if reason.lower() == 'q':
break
file.write(reason + '\n')
print("Thank you for sharing your thoughts!")
Thank you for sharing your thoughts!
Question 26¶
Addition: One common problem when prompting for numerical input occurs when people provide text instead of numbers. When you try to convert the input to an int, you’ll get a ValueError. Write a program that prompts for two numbers. Add them together and print the result. Catch the ValueError if either input value is not a number, and print a friendly error message. Test your program by entering two numbers and then by entering some text instead of a number.
while True:
try:
number1 = input("enter the first number: ")
number2 = input("enter the second number: ")
result = int(number1) + int(number2)
print("The sum of", number1, "and", number2, "is:", result)
break
except ValueError:
print("please enter valid numbers.")
print("thank you for using the program!")
The sum of 3 and 2 is: 5 thank you for using the program!
Question 27¶
Addition Calculator: Wrap your code from Question 26 in a while loop so the user can continue entering numbers even if they make a mistake and enter text instead of a number.
while True:
try:
number1 = input("Enter the first number: ")
number2 = input("Enter the second number: ")
result = int(number1) + int(number2)
print("The sum of", number1, "and", number2, "is:", result)
except ValueError:
print("Please enter valid numbers.")
else:
choice = input("Do you want to continue? (yes/no): ").lower()
if choice != 'yes':
break
print("Thank you for using the program!")
Please enter valid numbers. Please enter valid numbers. The sum of 6 and 7 is: 13 Thank you for using the program!
Question 28¶
Cats and Dogs: Make two files, cats.txt and dogs.txt. Store at least three names of cats in the first file and three names of dogs in the second file. Write a program that tries to read these files and print the contents of the file to the screen. Wrap your code in a try-except
block to catch the FileNotFound
error, and print a friendly message if a file is missing. Move one of the files to a different location on your system, and make sure the code in the except
block executes properly.
try:
with open('cats.txt', 'r') as cats_file:
print(" Cats ")
print(cats_file.read())
with open('dogs.txt', 'r') as dogs_file:
print(" Dogs ")
print(dogs_file.read())
except FileNotFoundError:
print("One or more files are missing.")
Cats winky pinky dinky Dogs shadrack mishack abidingo
try:
with open('cats.txt', 'r') as cats_file:
print(" Cats ")
print(cats_file.read())
with open('dogs.txt', 'r') as dogs_file:
print(" Dogs ")
print(dogs_file.read())
except FileNotFoundError:
print("One or more files are missing.")
Cats winky pinky dinky One or more files are missing.
Question 29¶
Silent Cats and Dogs: Modify your except block in Question 28 to fail silently if either file is missing.
try:
with open('cats.txt', 'r') as cats_file:
print(" Cats ")
print(cats_file.read())
with open('dogs.txt', 'r') as dogs_file:
print(" Dogs ")
print(dogs_file.read())
except FileNotFoundError:
pass
Cats winky pinky dinky
Question 30¶
Common Words: Visit Project Gutenberg (https://gutenberg.org/) and find a few texts you’d like to analyze. Download the text files for these works, or copy the raw text from your browser into a text file on your computer. You can use the count()
method to find out how many times a word or phrase appears in a string. For example, the following code counts the number of times 'row' appears in a string:
line = "Row, row, row your boat"
line.count("row")
2
line.lower().count("row")
3
Notice that converting the string to lowercase using lower() catches all appearances of the word you’re looking for, regardless of how it’s formatted.
Write a program that reads the files you found at Project Gutenberg and determines how many times the word the
appears in each text. This will be an approximation because it will also count words such as then
and there
. Try counting the
, with a space in the string, and see how much lower your count is.
def count_word_occurrences(file_path, word):
"""Count the occurrences of a word in a text file."""
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
words = content.split()
count = sum(1 for w in words if w.lower() == word.lower())
return count
except FileNotFoundError:
print(f"File {file_path} not found.")
return None
def main():
text_files = {
"This Side of Paradise": "This_Side_of_Paradise.txt",
"Walden": "Walden.txt",
"Adventures of Huckleberry Finn": "Huckleberry_Finn.txt"
}
for title, file_name in text_files.items():
count = count_word_occurrences(file_name, 'the')
if count is not None:
print(f"Occurrences of 'the' in '{title}': {count}")
main()
Occurrences of 'the' in 'This Side of Paradise': 3680 Occurrences of 'the' in 'Walden': 6604 Occurrences of 'the' in 'Adventures of Huckleberry Finn': 4424
def count_word_occurrences(file_path, word):
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
count_with_space = content.lower().count(' ' + word.lower() + ' ')
return count_with_space
except FileNotFoundError:
print(f"File {file_path} not found.")
return None
def main():
text_files = {
"This Side of Paradise": "This_Side_of_Paradise.txt",
"Walden": "Walden.txt",
"Adventures of Huckleberry Finn": "Huckleberry_Finn.txt"
}
for title, file_name in text_files.items():
count = count_word_occurrences(file_name, 'the')
if count is not None:
print(f"Occurrences of 'the' in '{title}': {count}")
main()
Occurrences of 'the' in 'This Side of Paradise': 3401 Occurrences of 'the' in 'Walden': 6139 Occurrences of 'the' in 'Adventures of Huckleberry Finn': 4120
def main():
text_files = {
"This Side of Paradise": "This_Side_of_Paradise.txt",
"Walden": "Walden.txt",
"Adventures of Huckleberry Finn": "Huckleberry_Finn.txt"
}
for title, file_name in text_files.items():
try:
with open(file_name, 'r', encoding='utf-8') as file:
content = file.read().lower()
count_with_space = content.count(' the ')
print(f"Occurrences of 'the' (with space) in '{title}': {count_with_space}")
except FileNotFoundError:
print(f"File {file_name} not found.")
if __name__ == "__main__":
main()
Occurrences of 'the' (with space) in 'This Side of Paradise': 3401 Occurrences of 'the' (with space) in 'Walden': 6139 Occurrences of 'the' (with space) in 'Adventures of Huckleberry Finn': 4120