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": 24,
"city": "Knoxville"
}
for key, value in person_info.items():
print(f"{key}: {value}")
first_name: Yuze last_name: Li age: 24 city: Knoxville
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 = {
"Ted": 6,
"Bob": 2,
"Zed": 15,
"Allen": 9,
"Tom": 13
}
for name, number in favorite_numbers.items():
print(f"{name}'s favorite number is {number}")
Ted's favorite number is 6 Bob's favorite number is 2 Zed's favorite number is 15 Allen's favorite number is 9 Tom's favorite number is 13
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": "Contains some known or unknown amounts of information that may be related to each other.",
"function": "A block of organized, reusable code that is used to perform a single, related action.",
"loop": "A programming construct that repeats a group of commands.",
"dictionary": "A collection of key-value pairs and information. ",
"list": "An ordered collection of items which is changeable and allows duplicate members."
}
for term, meaning in glossary.items():
print(f"{term}:\n {meaning}\n")
variable:
Contains some known or unknown amounts of information that may be related to each other.
function:
A block of organized, reusable code that is used to perform a single, related action.
loop:
A programming construct that repeats a group of commands.
dictionary:
A collection of key-value pairs and information.
list:
An ordered collection of items which is changeable and allows 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.update({
"class": "A blueprint for creating objects (a particular data structure), providing initial values for state (member variables) and implementations of behavior (member functions or methods).",
"inheritance": "A mechanism in which one class acquires the properties (methods and fields) of another.",
"module": "A file containing Python definitions and statements. The file name is the module name with the suffix .py added.",
"generator": " A special type of iterator that is defined with a function using the 'yield' keyword. It generates values on the fly and consumes less memory.",
"syntax": "The set of rules that defines the combinations of symbols that are considered to be correctly structured programs in that language."
})
for term, meaning in glossary.items():
print(f"{term}:\n {meaning}\n")
variable:
Contains some known or unknown amounts of information that may be related to each other.
function:
A block of organized, reusable code that is used to perform a single, related action.
loop:
A programming construct that repeats a group of commands.
dictionary:
A collection of key-value pairs and information.
list:
An ordered collection of items which is changeable and allows duplicate members.
class:
A blueprint for creating objects (a particular data structure), providing initial values for state (member variables) and implementations of behavior (member functions or methods).
inheritance:
A mechanism in which one class acquires the properties (methods and fields) of another.
module:
A file containing Python definitions and statements. The file name is the module name with the suffix .py added.
generator:
A special type of iterator that is defined with a function using the 'yield' keyword. It generates values on the fly and consumes less memory.
syntax:
The set of rules that defines the combinations of symbols that are considered to be correctly structured programs in that language.
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"
}
print("Sentences about each river:")
for river, country in rivers.items():
print(f"The {river} runs through {country}.")
print("\n")
print("Names of the rivers:")
for river in rivers.keys():
print(river)
print("\n")
print("Names of the countries:")
for country in rivers.values():
print(country)
Sentences about each river: The Nile runs through Egypt. The Amazon runs through Brazil. The Yangtze runs through China. Names of the rivers: Nile Amazon Yangtze Names of the 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": "13.515 million",
"fact": "The capital of Japan."
},
"Paris": {
"country": "France",
"population": "2.161 million",
"fact": "The capital of Japan France."
},
"Washington DC": {
"country": "United States",
"population": "8.419 million",
"fact": "The capital of United States."
}
}
for city, info in cities.items():
print(f"{city}:")
for key, value in info.items():
print(f" {key.capitalize()}: {value}")
print("\n")
Tokyo: Country: Japan Population: 13.515 million Fact: The capital of Japan. Paris: Country: France Population: 2.161 million Fact: The capital of Japan France. Washington DC: Country: United States Population: 8.419 million Fact: The capital of United States.
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_info = ("Subaru ")
print(f"Let me see if I can find you a {rental_car_info}.")
Let me see if I can find you a Subaru .
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.
number_of_people = int("9")
if number_of_people > 8:
print("You'll have to wait for a table.")
else:
print("Your table is ready.")
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 = int("10")
if number % 10 == 0:
print(f"{number} is a multiple of 10.")
else:
print(f"{number} is not a multiple of 10.")
10 is 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.
toppings = ["Tomato"]
for topping in toppings:
if topping.lower() == 'quit':
break
print(f"Adding {topping} to your pizza.")
Adding Tomato to your pizza.
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, I am learning about geo spatial functions in Python.")
display_message()
In this chapter, I am learning about geo spatial 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("Yashe")
One of my favorite books is Yashe.
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"The size of the shirt is {size} and the message printed on it is: '{message}'.")
make_shirt('M', 'Nike')
make_shirt(message='Adidas', size='L')
The size of the shirt is M and the message printed on it is: 'Nike'. The size of the shirt is L and the message printed on it is: 'Adidas'.
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='L', message='I love Python.'):
print(f"The size of the shirt is {size} and the message printed on it is: '{message}'.")
make_shirt()
make_shirt(size='M')
make_shirt(size='S', message='I love coding.')
The size of the shirt is L and the message printed on it is: 'I love Python.'. The size of the shirt is M and the message printed on it is: 'I love Python.'. The size of the shirt is S and the message printed on it is: 'I love coding.'.
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} is in {country}.")
describe_city('Reykjavik')
describe_city('Akureyri')
describe_city('Beijing', 'China')
Reykjavik is in Iceland. Akureyri is in Iceland. Beijing is in China.
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('Tokyo', 'Japan'))
Santiago, Chile Paris, France Tokyo, Japan
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_dict = {"artist": artist_name, "album": album_title}
if number_of_songs:
album_dict["songs"] = number_of_songs
return album_dict
album1 = make_album("The Beatles", "Oh my love")
album2 = make_album("Led Zeppelin", "Led Zeppelin IV")
album3 = make_album("Pink Floyd", "The Dark Side of the Moon")
print(album1)
print(album2)
print(album3)
album4 = make_album("Nirvana", "Nevermind", number_of_songs=4)
print(album4)
{'artist': 'The Beatles', 'album': 'Oh my love'}
{'artist': 'Led Zeppelin', 'album': 'Led Zeppelin IV'}
{'artist': 'Pink Floyd', 'album': 'The Dark Side of the Moon'}
{'artist': 'Nirvana', 'album': 'Nevermind', 'songs': 4}
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):
"""Build a dictionary containing album information."""
album_dict = {"artist": artist_name, "album": album_title}
if number_of_songs:
album_dict["songs"] = number_of_songs
return album_dict
user_albums = [
("The Beatles", "Oh my love"),
("Led Zeppelin", "Led Zeppelin IV"),
("quit", "quit")
]
for artist, title in user_albums:
if artist.lower() == 'quit' or title.lower() == 'quit':
print("See you!")
break
else:
album = make_album(artist, title)
print(album)
{'artist': 'The Beatles', 'album': 'Oh my love'}
{'artist': 'Led Zeppelin', 'album': 'Led Zeppelin IV'}
See you!
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)
text_messages = ["Hello, how are you?", "Goodbye!", "Have a great day!", "Thank you!."]
show_messages(text_messages)
Hello, how are you? Goodbye! Have a great day! Thank you!.
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 = []
while messages:
current_message = messages.pop()
print(current_message)
sent_messages.append(current_message)
return sent_messages
text_messages = ["Hello, how are you?", "Goodbye!", "Have a great day!", "Thank you"]
sent_messages = send_messages(text_messages[:])
print("\nOriginal messages:")
print(text_messages)
print("Sent messages:")
print(sent_messages)
Thank you Have a great day! Goodbye! Hello, how are you? Original messages: ['Hello, how are you?', 'Goodbye!', 'Have a great day!', 'Thank you'] Sent messages: ['Thank you', 'Have a great day!', 'Goodbye!', 'Hello, how are you?']
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'
with open(filename) as file_object:
contents = file_object.read()
print("Reading the entire file at once:")
print(contents)
print("\nLooping over the file object:")
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
print("\nStoring the lines in a list and working with them outside the 'with' block:")
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
Reading the entire file at once: In Python you can get a more relaxed programming experience and it will be helpful for you in all aspects. For example, web development, machine learning and artificial intelligence, scripting and automation, software development, and game development. Looping over the file object: In Python you can get a more relaxed programming experience and it will be helpful for you in all aspects. For example, web development, machine learning and artificial intelligence, scripting and automation, software development, and game development. Storing the lines in a list and working with them outside the 'with' block: In Python you can get a more relaxed programming experience and it will be helpful for you in all aspects. For example, web development, machine learning and artificial intelligence, scripting and automation, software development, and game development.
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 file_object:
lines = file_object.readlines()
for line in lines:
modified_line = line.replace('Python', 'C')
print(modified_line.rstrip())
In C you can get a more relaxed programming experience and it will be helpful for you in all aspects. For example, web development, machine learning and artificial intelligence, scripting and automation, software development, and game development.
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.
user_name = "Uz"
with open("guest.txt", "w") as file:
file.write(user_name)
print(f"{user_name} has been written to guest.txt.")
Uz 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.
user_names = ["Alice", "Bob", "Charlie"]
file_path = "guest_book.txt"
with open(file_path, "a") as file:
for user_name in user_names:
greeting = f"Hello, {user_name}! Welcome to our event."
print(greeting)
file.write(f"{user_name}\n")
Hello, Alice! Welcome to our event. Hello, Bob! Welcome to our event. Hello, Charlie! Welcome to our event.
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 = [
"convenient.",
"class requirements",
"app/web creating"
]
file_path = "programming_reasons.txt"
with open(file_path, "a") as file:
for reason in reasons:
file.write(f"{reason}\n")
print(f"Reasons have been added to {file_path}.")
Reasons have been added to programming_reasons.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.
def add_numbers():
inputs = [("4", "5"), ("three", "7")]
for input_pair in inputs:
try:
num1 = int(input_pair[0])
num2 = int(input_pair[1])
result = num1 + num2
print(f"The sum of {num1} and {num2} is {result}.")
except ValueError:
print("Error: Both inputs must be numbers. Please try again.")
add_numbers()
The sum of 4 and 5 is 9. Error: Both inputs must be numbers. Please try again.
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.
inputs = [("3", "4"), ("a", "5"), ("6", "b"), ("7", "8"), ("q",)]
for input_pair in inputs:
try:
if len(input_pair) == 1 and input_pair[0].lower() == 'q':
print("Quitting the program.")
break
num1, num2 = map(int, input_pair)
print(f"The sum of {num1} and {num2} is {num1 + num2}.")
except ValueError:
print("Error: Both inputs must be numbers. Please try again.")
The sum of 3 and 4 is 7. Error: Both inputs must be numbers. Please try again. Error: Both inputs must be numbers. Please try again. The sum of 7 and 8 is 15. Quitting 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.
filenames = ['cats.txt', 'dogs.txt']
for filename in filenames:
try:
with open(filename) as file_object:
print(f"Contents of {filename}:")
contents = file_object.read()
print(contents)
except FileNotFoundError:
print(f"Sorry, the file '{filename}' does not exist or cannot be found.")
Contents of cats.txt: Kiki Geegee Dongzhi Contents of dogs.txt: Doudou Vicky Ben
Question 29¶
Silent Cats and Dogs: Modify your except block in Question 28 to fail silently if either file is missing.
filenames = ['cats.txt', 'dogs.txt']
for filename in filenames:
try:
with open(filename) as file_object:
print(f"Contents of {filename}:")
contents = file_object.read()
print(contents)
except FileNotFoundError:
pass
Contents of cats.txt: Kiki Geegee Dongzhi Contents of dogs.txt: Doudou Vicky Ben
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 main():
text = '''Now the way of life that I preach is a habit to be acquired gradually by long and steady repetition. It is the practice of living for the day only, and for the day's work, Life in day-tight compartments. "Ah," I hear you say, "that is an easy matter, simple as Elisha's advice!" Not as I shall urge it, in words which fail to express the depth of my feelings as to its value. I started life in the best of all environments—in a parsonage, one of nine children. A man who has filled Chairs in four universities, has written a successful book, and has been asked to lecture at Yale, is supposed popularly to have brains of a special quality. A few of my intimate friends really know the truth about me, as I know it! Mine, in good faith I say it, are of the most mediocre character. But what about those professorships, etc.? Just habit, a way of life, an outcome of the day's work, the vital importance of which I wish to impress upon you with all the force at my command.'''
occurrences_nonspace = text.lower().split().count("the")
print(f"The word 'the' without spaces appears {occurrences_nonspace} times in the text.")
occurrences_space = text.lower().split().count(" the ")
print(f"The word 'the' with spaces appears {occurrences_space} times in the text.")
if __name__ == "__main__":
main()
The word 'the' without spaces appears 11 times in the text. The word 'the' with spaces appears 0 times in the text.