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 Colabbadge. 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.
# Create a dictionary to store information about a person
person_info = {
'first_name': 'Ryan',
'last_name': 'Willson',
'age': 30,
'city': 'Washington D.C.'
}
# Print each piece of information stored in the dictionary
print("First Name:", person_info['first_name'])
print("Last Name:", person_info['last_name'])
print("Age:", person_info['age'])
print("City:", person_info['city'])
First Name: Ryan Last Name: Willson Age: 30 City: Washington D.C.
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.
# Create a dictionary to store people's favorite numbers
favorite_numbers = {
'Ryan': 25,
'Jake': 42,
'Trevor': 7,
'Dylan': 8,
'Rylee': 16
}
# Print each person's name and their favorite number
for person, number in favorite_numbers.items():
print(f"{person}'s favorite number is {number}.")
Ryan's favorite number is 25. Jake's favorite number is 42. Trevor's favorite number is 7. Dylan's favorite number is 8. Rylee's favorite number is 16.
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.
# Create a glossary dictionary
glossary = {
'list': 'A collection of items, ordered and changeable, used to store multiple values in a single variable.',
'definition': 'A statement or description that explains the meaning of a word or the purpose of a concept in programming.',
'function': 'A reusable block of code that performs a specific task.',
'variable': 'A named storage location in a program that can hold a value.',
'loop': 'A control flow statement that allows code to be repeatedly executed.',
}
# Print each word and its meaning neatly formatted
for word, meaning in glossary.items():
print(f"{word}:\n{meaning}\n")
list: A collection of items, ordered and changeable, used to store multiple values in a single variable. definition: A statement or description that explains the meaning of a word or the purpose of a concept in programming. function: A reusable block of code that performs a specific task. variable: A named storage location in a program that can hold a value. loop: A control flow statement that allows code to be repeatedly executed.
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.
#Adding more python terms to the glossary
glossary.update({
'dictionary': 'A collection of key-value pairs, allowing efficient data retrieval.',
'module': 'A file containing Python definitions and statements, intended for reuse.',
'exception': 'An event that occurs during the execution of a program and disrupts the normal flow.',
'syntax': 'A set of rules that dictate how programs in a specific language are constructed.',
'algorithm': 'A step-by-step procedure or formula for solving a problem or accomplishing a task.'
})
# Print each word and its meaning using a loop
for word, meaning in glossary.items():
print(f"{word}:\n{meaning}\n")
list: A collection of items, ordered and changeable, used to store multiple values in a single variable. definition: A statement or description that explains the meaning of a word or the purpose of a concept in programming. function: A reusable block of code that performs a specific task. variable: A named storage location in a program that can hold a value. loop: A control flow statement that allows code to be repeatedly executed. dictionary: A collection of key-value pairs, allowing efficient data retrieval. module: A file containing Python definitions and statements, intended for reuse. exception: An event that occurs during the execution of a program and disrupts the normal flow. syntax: A set of rules that dictate how programs in a specific language are constructed. algorithm: A step-by-step procedure or formula for solving a problem or accomplishing a task.
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.
# Create a dictionary of major rivers and the countries they run through
rivers = {
'Mississippi River': 'United States of America',
'Amazon': 'Brazil',
'Nile': 'Egypt'
}
# Use a loop to print a sentence about each river
print("River Information:")
for river, country in rivers.items():
print(f"The {river} is located in {country}.")
# Use a loop to print the names of each river
print("\nNames of Rivers:")
for river in rivers.keys():
print(river)
# Use a loop to print the names of each country
print("\nNames of Countries:")
for country in rivers.values():
print(country)
River Information: The Mississippi River is located in United States of America. The Amazon is located in Brazil. The Nile is located in Egypt. Names of Rivers: Mississippi River Amazon Nile Names of Countries: United States of America Brazil Egypt
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.
# Create a dictionary of cities and their information
cities = {
'New York': {
'country': 'United States',
'population': "8.468 million",
'fact': 'The Statue of Liberty is located in New York Harbor.'
},
'Tokyo': {
'country': 'Japan',
'population': "13.96 million",
'fact': 'Tokyo is the most populous metropolitan area in the world.'
},
'Paris': {
'country': 'France',
'population': "2.161 million",
'fact': 'Paris is known as the "City of Light" and is famous for its art and culture.'
}
}
# Print the name of each city and its information
for city, info in cities.items():
print(f"\nCity: {city}")
print(f"Country: {info['country']}")
print(f"Population: {info['population']}")
print(f"Fact: {info['fact']}")
City: New York Country: United States Population: 8.468 million Fact: The Statue of Liberty is located in New York Harbor. City: Tokyo Country: Japan Population: 13.96 million Fact: Tokyo is the most populous metropolitan area in the world. City: Paris Country: France Population: 2.161 million Fact: Paris is known as the "City of Light" and is famous for its art and culture.
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.”
# Ask the user what kind of rental car they would like
rental_car = input("What kind of rental car would you like? ")
# Print a message based on the user's choice
print(f"Let me see if I can find you a {rental_car}.")
Let me see if I can find you a tacoma.
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.
# Ask the user how many people are in their dinner group
num_people = int(input("How many people are in your dinner group? "))
# Check the number of people and provide a response
if num_people > 8:
print("I'm sorry, but you'll have to wait for a table.")
else:
print("Your table is ready. Enjoy your meal!")
Your table is ready. Enjoy your meal!
Question 9¶
Multiples of Ten: Ask the user for a number, and then report whether the number is a multiple of 10 or not.
# Ask the user for a number
user_number = int(input("Please enter a number: "))
# Check if the number is a multiple of 10
if user_number % 10 == 0:
print(f"{user_number} is a multiple of 10.")
else:
print(f"{user_number} is not a multiple of 10.")
5 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.
# Initialize an empty list to store pizza toppings
pizza_toppings = []
# Prompt the user to enter pizza toppings
while True:
topping = input("Enter a pizza topping (type 'quit' to finish): ")
# Check if the user wants to quit
if topping.lower() == 'quit':
break
# Add the topping to the list and print a message
pizza_toppings.append(topping)
print(f"Adding {topping} to your pizza.")
# Print the final list of pizza toppings
print("\nYour pizza will have the following toppings:")
for topping in pizza_toppings:
print(f"- {topping}")
Adding bacon to your pizza. Adding pepperoni to your pizza. Your pizza will have the following toppings: - bacon - pepperoni
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.
# Define the display_message function
def message():
print("In this notebook, I am learning about Python functions and basic programming concepts.")
# Call the function to display the message
message()
In this notebook, I am learning about Python functions and basic programming concepts.
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.
# Define the favorite_book function
def favorite_book(title):
print(f"One of my favorite books is {title}.")
# Call the function with a book title
favorite_book("Jurassic Park")
One of my favorite books is Jurassic Park.
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.
# Define the make_shirt function
def make_shirt(size, message):
print(f"Creating a shirt of size {size} with the message: '{message}'.")
# Call the function once using positional arguments
make_shirt("Medium", "So Cool It Hurts")
# Call the function a second time using keyword arguments
make_shirt(size="Large", message="Python Lover")
Creating a shirt of size Medium with the message: 'So Cool It Hurts'. Creating a shirt of size Large with the message: 'Python Lover'.
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.
# Modified make_shirt function with default values
def make_shirt(size="Large", message="I love Python"):
print(f"Creating a shirt of size {size} with the message: '{message}'.")
# Create a large shirt with the default message
make_shirt()
# Create a medium shirt with the default message
make_shirt(size="Medium")
# Create a custom-sized shirt with a different message
make_shirt(size="Small", message="Python is Fun!")
Creating a shirt of size Large with the message: 'I love Python'. Creating a shirt of size Medium with the message: 'I love Python'. Creating a shirt of size Small with the message: 'Python is Fun!'.
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.
# Define the describe_city function with a default country
def describe_city(city, country="USA"):
print(f"{city} is in {country}.")
# Call the function for three different cities
describe_city("New York")
describe_city("Washington D.C.")
describe_city("Tokyo", "Japan")
New York is in USA. Washington D.C. is in USA. Tokyo is in Japan.
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}, {country}"
print(city_country("Tokyo", "Japan"))
print(city_country("New York", "USA"))
print(city_country("Paris", "France"))
Tokyo, Japan New York, USA Paris, France
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.
# Define the make_album function
def make_album(artist, title, songs=None):
album = {'artist': artist, 'title': title}
if songs is not None:
album['songs'] = songs
return album
# Make three dictionaries representing different albums
album1 = make_album("Imagine Dragons", "Night Visions", songs=13)
album2 = make_album("The Beatles", "Abbey Road", songs=17)
album3 = make_album("Ed Sheeran", "÷ (Divide)", songs=16)
# Print each return value to show the stored album information
print(album1)
print(album2)
print(album3)
album4 = make_album("John Williams", "Jurassic Park", songs=16)
print(album4)
{'artist': 'Imagine Dragons', 'title': 'Night Visions', 'songs': 13}
{'artist': 'The Beatles', 'title': 'Abbey Road', 'songs': 17}
{'artist': 'Ed Sheeran', 'title': '÷ (Divide)', 'songs': 16}
{'artist': 'John Williams', 'title': 'Jurassic Park', '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.
# Define the make_album function
def make_album(artist, title, songs=None):
album = {'artist': artist, 'title': title}
if songs is not None:
album['songs'] = songs
return album
albums = [
("Imagine Dragons", "Night Visions"),
("The Beatles", "Abbey Road"),
("Ed Sheeran", "÷ (Divide)"),
("end", "end")
]
for artist, title in albums:
if artist.lower() == 'end' or title.lower() == 'end':
print("bye")
break
else:
album = make_album(artist, title)
print(album)
{'artist': 'Imagine Dragons', 'title': 'Night Visions'}
{'artist': 'The Beatles', 'title': 'Abbey Road'}
{'artist': 'Ed Sheeran', 'title': '÷ (Divide)'}
bye
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.
# Define the show_messages function
def show_messages(messages):
for message in messages:
print(message)
# Create a list of short text messages
text_messages = [
"Hello!",
"How are you?",
"Python is fun!",
"Keep coding!",
"Have a great day!"
]
# Call the show_messages function with the list of messages
show_messages(text_messages)
Hello! How are you? Python is fun! Keep coding! Have a great day!
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.
# Define the send_messages function
def send_messages(messages, sent_messages):
while messages:
current_message = messages.pop()
print(f"Sending message: {current_message}")
sent_messages.append(current_message)
return sent_messages
# Create a list of short text messages
text_messages = [
"Hello!",
"How are you?",
"Python is fun!",
"Keep coding!",
"Have a great day!"
]
# Create an empty list to store sent messages
sent_messages = []
# Call the send_messages function with the list of messages
send_messages(text_messages, sent_messages)
# Print both lists to verify messages were moved correctly
print("\nOriginal messages:")
print(text_messages)
print("\nSent messages:")
print(sent_messages)
Sending message: Have a great day! Sending message: Keep coding! Sending message: Python is fun! Sending message: How are you? Sending message: Hello! Original messages: [] Sent messages: ['Have a great day!', 'Keep coding!', 'Python is fun!', 'How are you?', 'Hello!']
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.
filename = 'learning_python.txt'
# Read the entire file and print its contents
with open(filename) as text_file:
contents = text_file.read()
print("Read entire file:")
print(contents)
# Loop over the file object and print each line
print("\nLooping over the file object:")
with open(filename) as text_file:
for line in text_file:
print(line.rstrip())
# Store lines in a list and print outside the with block
print("\nLines stored in a list and printed outside the with block:")
with open(filename) as text_file:
lines = text_file.readlines()
# Strip to remove extra newline characters
for line in lines:
print(line.rstrip())
Read entire file: In Python you can define functions to encapsulate reusable code. In Python you can use dictionaries to store key-value pairs. In Python you can work with files using the built-in file handling capabilities. Looping over the file object: In Python you can define functions to encapsulate reusable code. In Python you can use dictionaries to store key-value pairs. In Python you can work with files using the built-in file handling capabilities. Lines stored in a list and printed outside the with block: In Python you can define functions to encapsulate reusable code. In Python you can use dictionaries to store key-value pairs. In Python you can work with files using the built-in file handling capabilities.
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.
filename = 'learning_python.txt'
with open(filename) as text_file:
file = text_file.readlines()
for line in file:
modified_line = line.replace('Python', 'C')
print(modified_line.rstrip())
In C you can define functions to encapsulate reusable code. In C you can use dictionaries to store key-value pairs. In C you can work with files using the built-in file handling capabilities.
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.
# Prompt the user for their name
user_name = input("Please enter your name: ")
# Write the user's name to guest.txt
with open('guest.txt', 'w') as file:
file.write(user_name)
print(f"Thank you, {user_name}! Your name has been written to guest.txt.")
Thank you, Brycen Harris! Your name has been written to guest.txt.
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.
# Open guest_book.txt in append mode to record visits
with open('guest_book.txt', 'a') as guest_book:
while True:
# Prompt the user for their name
user_name = input("Please enter your name (type 'quit' to exit): ")
# Check if the user wants to quit
if user_name.lower() == 'quit':
break
# Print a greeting to the screen
print(f"Welcome, {user_name}!")
# Write the user's visit to guest_book.txt
guest_book.write(f"{user_name}\n")
print("Thanks for visiting! Check guest_book.txt for recorded visits.")
Welcome, Brycen Harris! Welcome, Ryan Willson! Thanks for visiting! Check guest_book.txt for recorded visits.
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.
# Open poll_responses.txt in append mode to store responses
with open('poll_responses.txt', 'a') as poll_responses:
print("Welcome to the Programming Poll! Type 'quit' to exit.")
while True:
# Prompt the user for their reason for liking programming
reason = input("Why do you like programming? ")
# Check if the user wants to quit
if reason.lower() == 'quit':
break
# Write the user's reason to poll_responses.txt
poll_responses.write(f"{reason}\n")
print("Thank you for participating! Responses have been recorded in poll_responses.txt.")
Welcome to the Programming Poll! Type 'quit' to exit. Thank you for participating! Responses have been recorded in poll_responses.txt.
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:
# Prompt the user for two numbers
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
# Convert input to integers and add them together
result = int(num1) + int(num2)
# Print the result
print(f"The sum of {num1} and {num2} is: {result}")
# Break out of the loop after successful input
break
except ValueError:
# Handle ValueError if input is not a number
print("Invalid input. Please enter valid numbers.")
Invalid input. Please enter valid numbers. The sum of 6 and 8 is: 14
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:
# Prompt the user for two numbers
num1 = input("Enter the first number (or 'quit' to exit): ")
# Check if the user wants to quit
if num1.lower() == 'quit':
break
num2 = input("Enter the second number: ")
# Convert input to integers and add them together
result = int(num1) + int(num2)
# Print the result
print(f"The sum of {num1} and {num2} is: {result}")
except ValueError:
# Handle ValueError if input is not a number
print("Invalid input. Please enter valid numbers.")
The sum of 6 and 8 is: 14 The sum of 5 and 4 is: 9 The sum of 10 and 15 is: 25
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.
filenames = ['dogs.txt', 'cats.txt']
for filename in filenames:
try:
with open(filename) as text_file:
print(f"Contents of {filename}:")
contents = text_file.read()
print(contents)
print()
except FileNotFoundError:
print(f"Sorry, the file '{filename}' does not exist or cannot be found.")
Contents of dogs.txt: Grace Junior Mitsy Contents of cats.txt: Luna Milo Oliver
Question 29¶
Silent Cats and Dogs: Modify your except block in Question 28 to fail silently if either file is missing.
filenames = ['dogs.txt', 'cats.txt']
for filename in filenames:
try:
with open(filename) as text_file:
print(f"Contents of {filename}:")
contents = text_file.read()
print(contents)
print()
except FileNotFoundError:
pass
Contents of dogs.txt: Grace Junior Mitsy Contents of cats.txt: Luna Milo Oliver
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")
line.lower().count("row")
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_the(file_name, target_word):
try:
with open(file_name, 'r', encoding='utf-8') as file:
content = file.read()
# Count occurrences with a space
with_space = content.lower().count(target_word.lower())
# Count occurrences without a space
no_space = content.lower().count(target_word.lower() + " ")
print(f"The word '{target_word}' with space show up {with_space} times in the text file.")
print(f"The word '{target_word}' without a space shows up {no_space} times in the text file.")
except FileNotFoundError:
print(f"Sorry, the file '{filename}' does not exist or cannot be found.")
# Example usage for the gutenberg_file.txt
count_the("gutenberg_file.txt", "the")
The word 'the' with space show up 3151 times in the text file. The word 'the' without a space shows up 2215 times in the text file.