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': 'John',
'last_name': 'Conner',
'age': 28,
'city': 'New York'
}
print(f"First Name: {person_info['first_name']}")
print(f"Last Name: {person_info['last_name']}")
print(f"Age: {person_info['age']}")
print(f"City: {person_info['city']}")
First Name: John Last Name: Conner Age: 28 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.
numbers = {
'Borno': 7,
'Mou': 42,
'Tisha': 23,
'Jannatul': 8,
'Sumaya': 3
}
for name, number in numbers.items():
print(f"{name}'s favorite number is {number}.")
Borno's favorite number is 7. Mou's favorite number is 42. Tisha's favorite number is 23. Jannatul's favorite number is 8. Sumaya'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 storage location paired with an associated symbolic name.',
'loop': 'A programming structure that repeats a sequence of instructions.',
'function': 'A block of organized, reusable code that is used to perform a single, related action.',
'dictionary': 'A collection of key-value pairs that maps an immutable key to a value.',
'list': 'An ordered collection of items which is changeable, allowing duplicate members.'
}
for term, definition in glossary.items():
print(f"{term.title()}:{definition}\n")
Variable:A storage location paired with an associated symbolic name. Loop:A programming structure that repeats a sequence of instructions. Function:A block of organized, reusable code that is used to perform a single, related action. Dictionary:A collection of key-value pairs that maps an immutable key to a value. List:An ordered collection of items which is changeable, allowing 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 storage location paired with an associated symbolic name.',
'loop': 'A programming structure that repeats a sequence of instructions.',
'function': 'A block of organized, reusable code that is used to perform a single, related action.',
'dictionary': 'A collection of key-value pairs that maps an immutable key to a value.',
'list': 'An ordered collection of items which is changeable, allowing duplicate members.',
'tuple': 'An ordered collection of items which is unchangeable, allowing duplicate members.',
'set': 'An unordered collection of items that does not allow duplicate elements, useful for storing unique items.',
'conditional statement': 'A statement that is used to perform different actions based on different conditions, often expressed with if-else blocks.',
'comprehension': 'A concise way to create lists, dictionaries, sets, etc., using a single line of code.',
'module': 'A file containing Python definitions and statements. The file name is the module name with the suffix .py added.'
}
for term, definition in glossary.items():
print(f"{term.title()}:{definition}\n")
Variable:A storage location paired with an associated symbolic name. Loop:A programming structure that repeats a sequence of instructions. Function:A block of organized, reusable code that is used to perform a single, related action. Dictionary:A collection of key-value pairs that maps an immutable key to a value. List:An ordered collection of items which is changeable, allowing duplicate members. Tuple:An ordered collection of items which is unchangeable, allowing duplicate members. Set:An unordered collection of items that does not allow duplicate elements, useful for storing unique items. Conditional Statement:A statement that is used to perform different actions based on different conditions, often expressed with if-else blocks. Comprehension:A concise way to create lists, dictionaries, sets, etc., using a single line of code. Module:A file containing Python definitions and statements. The file name is the module name with the suffix .py added.
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 = {
'yellow river': 'china',
'brahmaputra': 'india',
'jamuna': 'bangladesh',
}
for river, country in rivers.items():
print(f"The {river.title()} runs through {country.title()}.")
print("Rivers mentioned:")
for river in rivers.keys():
print(f"- {river.title()}")
print("Countries mentioned:")
for country in rivers.values():
print(f"- {country.title()}")
The Yellow River runs through China. The Brahmaputra runs through India. The Jamuna runs through Bangladesh. Rivers mentioned: - Yellow River - Brahmaputra - Jamuna Countries mentioned: - China - India - Bangladesh
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 = {
'Dhaka': {
'country': 'Bangladesh',
'population': '11 million',
'fact': 'Dhaka is known for its traffic jam and masala curry food.'
},
'Paris': {
'country': 'France',
'population': '2.1 million',
'fact': 'Paris is famous for its art, fashion, gastronomy, and culture.'
},
'Cairo': {
'country': 'Egypt',
'population': '9.5 million',
'fact': 'Cairo is home to the nearest ancient wonders of the world, the Great Pyramids.'
}
}
for city, info in cities.items():
print(f"City: {city}")
for key, value in info.items():
print(f"{key.capitalize()}: {value}")
print()
City: Dhaka Country: Bangladesh Population: 11 million Fact: Dhaka is known for its traffic jam and masala curry food. City: Paris Country: France Population: 2.1 million Fact: Paris is famous for its art, fashion, gastronomy, and culture. City: Cairo Country: Egypt Population: 9.5 million Fact: Cairo is home to the nearest ancient wonders of the world, the Great Pyramids.
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_pref = input("What kind of rental car would you like? ")
print(f"Let me see if I can find you a {car_pref}.")
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(input("How many people are in your dinner group? "))
if number_of_people > 8:
print("Sorry, you'll have to wait for a table.")
else:
print("Your table is ready.")
Sorry, 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(input("Please enter a number: "))
if number % 10 == 0:
print(f"The number {number} is a multiple of 10.")
else:
print(f"The number {number} is not a multiple of 10.")
The number 56 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("Add this topping to your pizza: ")
if topping == 'quit':
break
else:
print(f"You'll add {topping} to your pizza.")
You'll add beef to your pizza. You'll add banana 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("I'm learning Python Packages in this chapter!")
display_message()
I'm learning Python Packages in this chapter!
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("It Wasn't About Slavery")
One of my favorite books is It Wasn't About Slavery.
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 the size of the shirt and the message printed on it."""
print(f"Making a {size} t-shirt with the message: '{message}'")
make_shirt('large', 'Python is Super!')
make_shirt(message='Code More, Worry Less', size='medium')
Making a large t-shirt with the message: 'Python is Super!' Making a medium t-shirt with the message: 'Code More, Worry Less'
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'):
"""Prints the size of the shirt and the message printed on it, with defaults."""
print(f"Making a {size} t-shirt with the message: '{message}'")
make_shirt()
make_shirt(size='medium')
make_shirt(size='small', message='Python is time consuming!')
Making a large t-shirt with the message: 'I love Python' Making a medium t-shirt with the message: 'I love Python' Making a small t-shirt with the message: 'Python is time consuming!'
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('London', 'England')
describe_city('Tokyo', 'Japan')
Reykjavik is in Iceland. London is in England. 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('Wilmington', 'Delaware'))
print(city_country('Knoxville', 'Tennessee'))
print(city_country('Dhaka', 'Bangladesh'))
Wilmington, Delaware Knoxville, Tennessee Dhaka, Bangladesh
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,
'title': album_title,
}
if number_of_songs:
album_dict['Tracks'] = number_of_songs
return album_dict
album_1 = make_album('Motorhead', 'The King')
album_2 = make_album('Breaking Benjamin', 'Diary of Jane')
album_3 = make_album('Dead By April', 'Memory', number_of_songs=7)
print(album_1)
print(album_2)
print(album_3)
{'artist': 'Motorhead', 'title': 'The King'}
{'artist': 'Breaking Benjamin', 'title': 'Diary of Jane'}
{'artist': 'Dead By April', 'title': 'Memory', 'Tracks': 7}
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):
album_dict = {
'artist': artist_name,
'title': album_title,
}
return album_dict
while True:
artist_name = input("Enter the Artist's name: ")
if artist_name == 'quit':
break
album_title = input("Album title: ")
if album_title == 'quit':
break
album = make_album(artist_name, album_title)
print(album)
{'artist': 'tayor', 'title': 'red'}
{'artist': 'breaking benjamin', 'title': 'diary of jane'}
{'artist': 'john', 'title': 'contryroad'}
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):
"""Print each message in the list."""
for message in messages:
print(message)
messages = [
'Hello, how are you?',
'Don’t forget to bring your umbrella today!',
'Did you complete the Python assignment?',
'Good morning! Have a great day!',
'Can we meet for coffee tomorrow?'
]
show_messages(messages)
Hello, how are you? Don’t forget to bring your umbrella today! Did you complete the Python assignment? Good morning! Have a great day! Can we meet for coffee tomorrow?
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(0)
print(f"Sending message: {current_message}")
sent_messages.append(current_message)
messages = [
"Hello, how are you doing today?",
"Hows your wife!",
"Hope you will do well in this semester!",
"Bye, see you tomorrow!",
]
sent_messages = []
send_messages(messages, sent_messages)
print("\nFinal Lists:")
print("Original Messages:")
for message in messages:
print(message)
print("\nSent Messages:")
for sent_message in sent_messages:
print(sent_message)
Sending message: Hello, how are you doing today? Sending message: Hows your wife! Sending message: Hope you will do well in this semester! Sending message: Bye, see you tomorrow! Final Lists: Original Messages: Sent Messages: Hello, how are you doing today? Hows your wife! Hope you will do well in this semester! Bye, see you tomorrow!
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 at once:")
print(contents)
print("\nLooping over the file object:")
with open('learning_python.txt') as file_object:
for line in file_object:
print(line.rstrip())
print("\nWorking with the lines outside the 'with' block:")
with open('learning_python.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
Reading the entire file at once: In Python, you can create variables to store information. In Python, you can use loops to perform repetitive tasks efficiently. In Python, you can use functions to organize your code into reusable blocks. In Python, you can work with lists to store sequences of information. In Python, you can use dictionaries to connect pieces of related information. Looping over the file object: In Python, you can create variables to store information. In Python, you can use loops to perform repetitive tasks efficiently. In Python, you can use functions to organize your code into reusable blocks. In Python, you can work with lists to store sequences of information. In Python, you can use dictionaries to connect pieces of related information. Working with the lines outside the 'with' block: In Python, you can create variables to store information. In Python, you can use loops to perform repetitive tasks efficiently. In Python, you can use functions to organize your code into reusable blocks. In Python, you can work with lists to store sequences of information. In Python, you can use dictionaries to connect pieces of related information.
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', 'JAVA')
with open('learning_python.txt', 'r') as file:
lines = file.readlines()
print("\nReplaced Python with JAVA:\n")
for line in lines:
modified_line = line.replace('Python', 'JAVA')
print(modified_line.strip())
Replaced Python with JAVA: In JAVA, you can create variables to store information. In JAVA, you can use loops to perform repetitive tasks efficiently. In JAVA, you can use functions to organize your code into reusable blocks. In JAVA, you can work with lists to store sequences of information. In JAVA, you can use dictionaries to connect pieces of related information.
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(f"Hello, {name}! Your name has been written to guest.txt.")
Hello, metaliguns! 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.
filename = 'guest_book.txt'
while True:
name = input("Please enter your name (or type 'exit' to end): ")
if name.lower() == 'exit':
print("\nThank you for visiting!")
break
print(f"Hello, {name}! Welcome to our guest book.")
with open('guest_book.txt', 'a') as file:
file.write(name + '\n')
print("Your visit has been recorded in the guest_book.txt")
Hello, shkaib! Welcome to our guest book. Your visit has been recorded in the guest_book.txt Hello, akib! Welcome to our guest book. Your visit has been recorded in the guest_book.txt Hello, nishi! Welcome to our guest book. Your visit has been recorded in the guest_book.txt Hello, borno! Welcome to our guest book. Your visit has been recorded in the guest_book.txt 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.
filename = 'Programming_poll.txt'
while True:
reason = input("Why do you like programming? (or type 'exit' to end): ")
if reason.lower() == 'exit':
print("\nThank you for sharing your reasons!")
break
with open('programming_poll_responses.txt', 'a') as file:
file.write(reason + '\n')
print("Programming poll responses have been saved to programming_poll_responses.txt.")
Thank you for sharing your reasons! Programming poll responses have been saved to programming_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:
number_1 = int(input("Enter the first number: "))
number_2 = int(input("Enter the second number: "))
result = number_1 + number_2
print(f"The sum of {number_1} and {number_2} is: {result}")
break
except ValueError:
print("Error: Please enter valid numbers Here.")
Error: Please enter valid numbers Here. Error: Please enter valid numbers Here. Error: Please enter valid numbers Here. Error: Please enter valid numbers Here. The sum of 373 and 383 is: 756
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:
first_number = input("\nEnter the first number: ")
if first_number.lower() == 'quit':
break
first_number = float(first_number)
second_number = input("Enter the second number: ")
if second_number.lower() == 'quit':
break
second_number = float(second_number)
result = first_number + second_number
print(f"The result of adding {first_number} and {second_number} is {result}.")
except ValueError:
print("Oops! That was not a valid number. Please try again.")
Oops! That was not a valid number. Please try again. The result of adding 23.0 and 232.0 is 255.0. The result of adding 23.0 and 8239.0 is 8262.0. The result of adding 3223.0 and 23.0 is 3246.0.
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 cat_file:
print("Cat Names:")
for line in cat_file:
print(line.strip())
except FileNotFoundError:
print(f"cats.txt file not found. Check the file location")
try:
with open('dogs.txt', 'r') as dog_file:
print("\nDog Names:")
for line in dog_file:
print(line.strip())
except FileNotFoundError:
print("\ndogs.txt file not found. Please check the file location.")
Cat Names: kitty meni mewmew dogs.txt file not found. Please check the file location.
try:
with open('cats.txt', 'r') as cat_file:
print("Cat Names:")
for line in cat_file:
print(line.strip())
except FileNotFoundError:
print(f"cats.txt file not found. Check the file location")
try:
with open('dogs.txt', 'r') as dog_file:
print("\nDog Names:")
for line in dog_file:
print(line.strip())
except FileNotFoundError:
print("\ndogs.txt file not found. Please check the file location.")
Cat Names: kitty meni mewmew dogs.txt file not found. Please check the file location.
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:
cats_content = cats_file.read()
print("\nContents of cats.txt:")
print(cats_content)
except FileNotFoundError:
pass
try:
with open('dogs.txt', 'r') as dogs_file:
dogs_content = dogs_file.read()
print("\nContents of dogs.txt:")
print(dogs_content)
except FileNotFoundError:
pass
Contents of cats.txt: kitty meni mewmew
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.
import os
def count_the(file_path, word):
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read().lower()
count_with_space = text.count(word)
count_without_space = text.count(word + ' ')
return count_with_space, count_without_space
def main():
file_path = r'D:\spring 24\software design\labs\lab5_book.txt'
word_to_search = 'the'
count_with_space, count_without_space = count_the(file_path, word_to_search)
print(f'File: lab5_book.txt')
print(f'Count of "{word_to_search}" with space: {count_with_space}')
print(f'Count of "{word_to_search}" without space: {count_without_space}')
if __name__ == '__main__':
main()
File: lab5_book.txt Count of "the" with space: 1496 Count of "the" without space: 893