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.
person_info = {
"first_name": "yuze",
"last_name": "Li",
"age": 30,
"city": "New York"
}
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: yuze Last Name: Li Age: 30 City: 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 = {
"John": 7,
"Han": 4,
"Sarah": 11,
"Thomas": 14,
"Li": 6
}
for person, number in favorite_numbers.items():
print(person + "'s favorite number is:", number)
John's favorite number is: 7 Han's favorite number is: 4 Sarah's favorite number is: 11 Thomas's favorite number is: 14 Li's favorite number is: 6
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 container for storing data value.",
"function": "A block of code that only runs when it is called.",
"method": "A function that is associated with an object in Object-Oriented Programming (OOP).",
"loop": "A control flow statement for specifying iteration.",
"module": "A file containing Python definitions and statements intended for use in other Python programs."
}
for word, meaning in glossary.items():
print(word + ":")
print(meaning + "\n")
variable: A container for storing data value. function: A block of code that only runs when it is called. method: A function that is associated with an object in Object-Oriented Programming (OOP). loop: A control flow statement for specifying iteration. module: A file containing Python definitions and statements intended for use in other Python programs.
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 container for storing data value.",
"function": "A block of code that only runs when it is called.",
"method": "A function that is associated with an object in Object-Oriented Programming (OOP).",
"loop": "A control flow statement for specifying iteration.",
"module": "A file containing Python definitions and statements intended for use in other Python programs."
}
glossary.update({
"class": "A blueprint for creating objects, providing initial values for state (member variables), and implementations of behavior (member functions or methods).",
"object": "An instance of a class. It is a basic unit of Object-Oriented Programming (OOP).",
"list": "A collection which is ordered and changeable.",
"inheritance": "A mechanism in which one class inherits the properties and behaviors of another class.",
"dictionary": "A collection which is unordered, changeable, and indexed."
})
# Loop through the glossary to print each word and its meaning
for word, meaning in glossary.items():
print(word + ":")
print(meaning + "\n")
variable: A container for storing data value. function: A block of code that only runs when it is called. method: A function that is associated with an object in Object-Oriented Programming (OOP). loop: A control flow statement for specifying iteration. module: A file containing Python definitions and statements intended for use in other Python programs. class: A blueprint for creating objects, providing initial values for state (member variables), and implementations of behavior (member functions or methods). object: An instance of a class. It is a basic unit of Object-Oriented Programming (OOP). list: A collection which is ordered and changeable. inheritance: A mechanism in which one class inherits the properties and behaviors of another class. dictionary: A collection which is unordered, changeable, and indexed.
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.
rivers = {
"Nile": "Egypt",
"Amazon": "Brazil",
"Yangtze": "China"
}
for river, country in rivers.items():
print(f"The {river} runs through {country}.")
print("\nRivers:")
for river in rivers.keys():
print(river)
print("\nCountries:")
for country in rivers.values():
print(country)
The Nile runs through Egypt. The Amazon runs through Brazil. The Yangtze runs through China. Rivers: Nile Amazon Yangtze Countries: Egypt Brazil China
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": "approximately 14 million",
"fact": "Tokyo is the largest metropolitan area in the world."
},
"New York City": {
"country": "United States",
"population": "approximately 8.4 million",
"fact": "New York City is often referred to as the cultural, financial, and media capital of the world."
},
"London": {
"country": "United Kingdom",
"population": "approximately 9 million",
"fact": "London has four UNESCO World Heritage Sites: The Palace of Westminster, Westminster Abbey, the Tower of London, and Maritime Greenwich."
}
}
for city, info in cities.items():
print(city + ":")
for key, value in info.items():
print(f"{key.capitalize()}: {value}")
print()
Tokyo: Country: Japan Population: approximately 14 million Fact: Tokyo is the largest metropolitan area in the world. New York City: Country: United States Population: approximately 8.4 million Fact: New York City is often referred to as the cultural, financial, and media capital of the world. London: Country: United Kingdom Population: approximately 9 million Fact: London has four UNESCO World Heritage Sites: The Palace of Westminster, Westminster Abbey, the Tower of London, and Maritime Greenwich.
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.”
car_preference = "SUV"
print(f"Let me see if I can find you a {car_preference}.")
Let me see if I can find you a SUV.
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.
num_people = 9
if num_people > 8:
print("I'm sorry, but you'll have to wait for a table.")
else:
print("Your table is ready.")
I'm sorry, but you'll 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 = 11
if number % 10 == 0:
print(f"{number} is a multiple of 10.")
else:
print(f"{number} is not a multiple of 10.")
11 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 = ["Pepperoni", "Mushrooms", "Onions", "Sausage", "Bacon"]
for topping in pizza_toppings:
print(f"Adding {topping} to your pizza.")
print("Your pizza will have the following toppings:")
for topping in pizza_toppings:
print("- " + topping)
Adding Pepperoni to your pizza. Adding Mushrooms to your pizza. Adding Onions to your pizza. Adding Sausage to your pizza. Adding Bacon to your pizza. Your pizza will have the following toppings: - Pepperoni - Mushrooms - Onions - Sausage - Bacon
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():
print("In this chapter, we are learning about Python basic and more functions.")
display_message()
In this chapter, we are learning about Python basic and more functions.
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("pan long")
One of my favorite books is pan long.
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):
print(f"A {size}-sized shirt will be made with the message: '{message}'.")
make_shirt("medium", "What's up.")
make_shirt(size="large", message="What's up.")
A medium-sized shirt will be made with the message: 'What's up.'. A large-sized shirt will be made with the message: 'What's up.'.
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 shirt"):
print(f"A {size}-sized shirt will be made with the message: '{message}'.")
make_shirt()
make_shirt(size="medium")
make_shirt(size="small", message="What's up!")
A large-sized shirt will be made with the message: 'I love shirt'. A medium-sized shirt will be made with the message: 'I love shirt'. A small-sized shirt will be made with the message: 'What's up!'.
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="Unknown"):
print(f"{city} is in {country}.")
describe_city("knoxville", "United States")
describe_city("Shanghai", "China")
describe_city("New York City", "United States")
knoxville is in United States. Shanghai is in China. New York City is in United States.
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("Santiago", "Chile"))
print(city_country("Paris", "France"))
print(city_country("Shanghai", "China"))
Santiago, Chile Paris, France Shanghai, China
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_title
}
if number_of_songs:
album["number_of_songs"] = number_of_songs
return album
album1 = make_album("Jay", "F")
print(album1)
album2 = make_album("TT", "B", 12)
print(album2)
album3 = make_album("Miz", "C", 8)
print(album3)
{'artist': 'Jay', 'title': 'F'}
{'artist': 'TT', 'title': 'B', 'number_of_songs': 12}
{'artist': 'Miz', 'title': 'C', 'number_of_songs': 8}
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):
return {"artist": artist_name, "title": album_title}
albums = [
("Jay", "A"),
("TT", "B"),
("Wiz", "C")
]
for artist, title in albums:
album_info = make_album(artist, title)
print(album_info)
{'artist': 'Jay', 'title': 'A'}
{'artist': 'TT', 'title': 'B'}
{'artist': 'Wiz', 'title': 'C'}
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 = [
"Hello, how are you?",
"Don't forget to buy groceries.",
"Meeting at 3 PM today.",
"Happy birthday!"
]
show_messages(messages)
Hello, how are you? Don't forget to buy groceries. Meeting at 3 PM today. Happy birthday!
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 send_messages(messages):
sent_messages = []
for message in messages:
print(message)
sent_messages.append(message)
return sent_messages
messages = [
"Hello, how are you?",
"Don't forget to buy groceries.",
"Meeting at 3 PM today.",
"Happy birthday!"
]
sent_messages = send_messages(messages)
print("\nOriginal messages list:")
print(messages)
print("\nSent messages list:")
print(sent_messages)
Hello, how are you? Don't forget to buy groceries. Meeting at 3 PM today. Happy birthday! Original messages list: ['Hello, how are you?', "Don't forget to buy groceries.", 'Meeting at 3 PM today.', 'Happy birthday!'] Sent messages list: ['Hello, how are you?', "Don't forget to buy groceries.", 'Meeting at 3 PM today.', 'Happy birthday!']
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.
with open('learning_python.txt') as file_object:
contents = file_object.read()
print("Reading the entire file:")
print(contents)
print("\nReading line by line:")
with open('learning_python.txt') as file_object:
for line in file_object:
print(line.strip())
print("\nReading using a list:")
with open('learning_python.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.strip())
Reading the entire file: In Python you can build you code. In Python you can clean data. In Python you can create data In Python you can create function. In Python you can have fun. In Python you can find data stat. Reading line by line: In Python you can build you code. In Python you can clean data. In Python you can create data In Python you can create function. In Python you can have fun. In Python you can find data stat. Reading using a list: In Python you can build you code. In Python you can clean data. In Python you can create data In Python you can create function. In Python you can have fun. In Python you can find data stat.
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') as file_object:
for line in file_object:
modified_line = line.replace('Python', 'R')
print(modified_line.rstrip())
In R you can build you code. In R you can clean data. In R you can create data In R you can create function. In R you can have fun. In R you can find data stat.
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 = "John Li"
with open('guest.txt', 'w') as file_object:
file_object.write(name)
print("Your name has been written to guest.txt.")
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.
names = ["Alice", "Bob", "Charlie"]
for name in names:
if name.lower() == 'quit':
break
print(f"Welcome, {name}!")
with open('guest_book.txt', 'a') as file_object:
file_object.write(f"{name}\n")
print("Thank you for visiting!")
Welcome, Alice! Welcome, Bob! Welcome, Charlie! 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.
reasons = ["It's creative.", "It's challenging.", "It's useful."]
for reason in reasons:
if reason.lower() == 'quit':
break
with open('programming_reasons.txt', 'a') as file_object:
file_object.write(f"{reason}\n")
print("Thank you for sharing your reasons!")
Thank you for sharing your reasons!
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.
try:
num1 = 5
num2 = 10
result = num1 + num2
print(f"The sum of {num1} and {num2} is {result}.")
except ValueError:
print("Error: Please enter valid numerical inputs.")
print("Program finished.")
The sum of 5 and 10 is 15. Program finished.
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.
numbers = [(5, 10), (15, 20), (25, 30)]
for num1, num2 in numbers:
try:
result = num1 + num2
print(f"The sum of {num1} and {num2} is {result}.")
except ValueError:
print("Error: Please enter valid numerical inputs.")
else:
# Simulated choice
choice = 'yes' # Assuming the user wants to continue
if choice.lower() != 'yes':
break
print("Program finished.")
The sum of 5 and 10 is 15. The sum of 15 and 20 is 35. The sum of 25 and 30 is 55. Program finished.
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.
file_names = ['cats.txt', 'dogs.txt']
for file_name in file_names:
try:
with open(file_name) as file_object:
print(f"Contents of {file_name}:")
contents = file_object.read()
print(contents)
except FileNotFoundError:
print(f"Sorry, the file '{file_name}' does not exist or is in a different location.")
Contents of cats.txt: Siamese Persian Maine Coon Contents of dogs.txt: Labrador Retriever German Shepherd Golden Retriever
Question 29¶
Silent Cats and Dogs: Modify your except block in Question 28 to fail silently if either file is missing.
file_names = ['cats.txt', 'dogs.txt']
for file_name in file_names:
try:
with open(file_name) as file_object:
print(f"Contents of {file_name}:")
contents = file_object.read()
print(contents)
except FileNotFoundError:
pass
print("Program finished.")
Contents of cats.txt: Siamese Persian Maine Coon Contents of dogs.txt: Labrador Retriever German Shepherd Golden Retriever Program finished.
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_name, word):
with open(file_name, 'r', encoding='utf-8') as file:
text = file.read()
text_lower = text.lower()
count_with_space = text_lower.count(f' {word} ')
count_at_beginning = text_lower.startswith(word)
count_at_end = text_lower.endswith(word)
total_count = text_lower.count(word)
return count_with_space, count_at_beginning, count_at_end, total_count
file_names = ['book.txt']
word = 'there'
for file_name in file_names:
count_with_space, count_at_beginning, count_at_end, total_count = count_word_occurrences(file_name, word)
print(f"File: {file_name}")
print(f"Occurrences of ' {word} ': {count_with_space}")
print(f"Occurrences of '{word}' at the beginning: {count_at_beginning}")
print(f"Occurrences of '{word}' at the end: {count_at_end}")
print(f"Total occurrences of '{word}': {total_count}")
print()
File: book.txt Occurrences of ' there ': 1 Occurrences of 'there' at the beginning: False Occurrences of 'there' at the end: False Total occurrences of 'there': 4