Lab 5¶
Submission instructions¶
- Download the notebook from https://geosdemo.gishub.org/labs/lab5
- Complete the lab questions
- Restart Kernel and Run All Cells
- Upload the notebook to your GitHub repository
- Make sure the notebook has an
Open In Colab
badge. Click on the badge to make sure your notebook can be opened in Colab. - Submit the link to the notebook on your GitHub repository to Canvas
from datetime import datetime
now = datetime.now()
print(f"Submitted time: {now}")
Submitted time: 2023-03-22 21:47:18.128182
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 = {'first_name': 'willie', 'last_name': 'nelson', 'age': '21', 'city':'gatlinburg'}
for key, value in person.items():
print(f'{key} --> {value}')
first_name --> willie last_name --> nelson age --> 21 city --> gatlinburg
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.
fav_numbers = {'will':'77','jenna':'8','kevin':'7','robby':'50','parker':'13'}
for key, value in fav_numbers.items():
print(f'{key} --> {value}')
will --> 77 jenna --> 8 kevin --> 7 robby --> 50 parker --> 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.
words = {'sum': 'adds all values of choice', 'print':'displays select code when ran', 'append':'used to add item to a list', 'pop':'used to take item out of list', 'title':'used to upercase the first letter in every output'}
print(f"sum: {words['sum']}")
print(f"\nprint: {words['print']}")
print(f"\nappend: {words['append']}")
print(f"\npop: {words['pop']}")
print(f"\ntitle: {words['title']}")
sum: adds all values of choice print: displays select code when ran append: used to add item to a list pop: used to take item out of list title: used to upercase the first letter in every output
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.
words = {'sum': 'adds all values of choice', 'print':'displays select code when ran', 'append':'used to add item to a list', 'pop':'used to take item out of list', 'title':'used to upercase the first letter in every output'}
for key, value in words.items():
print(f"\n{key}:")
print(f"\t{value}")
sum: adds all values of choice print: displays select code when ran append: used to add item to a list pop: used to take item out of list title: used to upercase the first letter in every output
words_2 = {'sum': 'adds all values of choice', 'print':'displays select code when ran', 'append':'used to add item to a list', 'pop':'used to take item out of list', 'title':'used to upercase the first letter in every output', 'upper':'will uppercase selected code', 'def': 'starts the definition of a function', 'del':'deletes selected code from previous lists', 'input':'allows user to type in information to be used or saved', 'type':'identifies what a certain variable is'}
for key, value in words_2.items():
print(f"\n{key}:")
print(f"\t{value}")
sum: adds all values of choice print: displays select code when ran append: used to add item to a list pop: used to take item out of list title: used to upercase the first letter in every output upper: will uppercase selected code def: starts the definition of a function del: deletes selected code from previous lists input: allows user to type in information to be used or saved type: identifies what a certain variable is
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.
riv = {'mississippi river':'USA', 'amazon river':'brazil', 'tigris river':'turkey'}
for key, value in riv.items():
print(f"\nThe {key.title()} runs through {value.title()}.")
The Mississippi River runs through Usa. The Amazon River runs through Brazil. The Tigris River runs through Turkey.
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 = {
'nashville':{'country':'USA','population':'678,448','fact':'largest city in Tennessee'},
'knoxville':{'country':'USA','population':'188,085','fact':'The University of Tennessee is located in Knoxville.'},
'new york city':{'country':'USA','population':'8.4 million','fact':'the most populated city in the United States'}
}
for city, info in cities.items():
print(f'{city.title()}:')
print(f'\tCountry: {info["country"]}')
print(f'\tPopulation: {info["population"]}')
print(f'\tFact: {info["fact"]}')
Nashville: Country: USA Population: 678,448 Fact: largest city in Tennessee Knoxville: Country: USA Population: 188,085 Fact: The University of Tennessee is located in Knoxville. New York City: Country: USA Population: 8.4 million Fact: the most populated city in the 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.”
car = input('What kind of rental car would you like?: ')
print(f'\nLet me see if I can find you a(n) {car}.')
Let me see if I can find you a(n) Ford.
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.
seating = int(input("How many people are in your party? \n "))
if seating < 8:
print('Your table is now ready!')
else:
print("You will have to wait 5 days for a table :(")
You will have to wait 5 days 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.
num = int(input('Enter a number, and I will tell you if it is a multiple of 10: '))
if num % 10 == 0:
print('this number is a multiple of 10')
else:
print('this number is not a multiple of 10')
this number 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.
pizzatop = '\nLet me know what pizza toppings you would like to have: '
pizzatop += 'When you are done, type "quit" to end the program.'
message = ''
while message != 'quit':
message = input(pizzatop)
if message != 'quit':
print(f'\nwe are adding: {message}')
we are adding: pepp we are adding: cheese we are adding: mushrooms
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 am learning about Python.')
display_message()
I am learning about 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(book):
"""Displays my favorite book."""
print(f'One of my favorite books is {book.title()}.')
favorite_book('prisoner B-3087')
One of my favorite books is Prisoner B-3087.
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(shirt_size, shirt_message):
"""Displays shirt information"""
print(f'\nThe shirt size must be {shirt_size}, and it should say {shirt_message}.')
make_shirt('small', 'GO VOLS!')
make_shirt(shirt_size='small', shirt_message='GO VOLS!')
The shirt size must be small, and it should say GO VOLS!. The shirt size must be small, and it should say GO VOLS!.
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, message='I love Python'):
"""Displays shirt information"""
print(f"The shirt size is {size}, and it should say {message}.")
make_shirt('medium')
The shirt size is medium, and it should say I love Python.
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='USA'):
"""Displays city within a country."""
print(f'\n{city} is in {country}.')
describe_city('Los Angeles')
describe_city('Nashville')
describe_city('Mexico City', 'Mexico')
Los Angeles is in USA. Nashville is in USA. Mexico City is in Mexico.
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):
"""Displays city and country"""
print(f'{city}, {country}')
city_country('San Francisco', 'USA')
city_country('Atlanta', 'USA')
city_country('Bejing', 'China')
San Francisco, USA Atlanta, USA Bejing, 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, album_title):
"""Return a dictionary for an album dictionary"""
music_album = {'artist': artist, 'album title': album_title}
return music_album
album_dict = make_album('Radiohead', 'Pablo Honey')
print(album_dict)
album_dict = make_album('The Beatles', 'Rubber Soul')
print(album_dict)
album_dict = make_album('Gordon Lightfoot', 'Sundown')
print(album_dict)
{'artist': 'Radiohead', 'album title': 'Pablo Honey'} {'artist': 'The Beatles', 'album title': 'Rubber Soul'} {'artist': 'Gordon Lightfoot', 'album title': 'Sundown'}
def make_album(artist, album_title, music = '0'):
"""Return a dictionary for an album dictionary"""
music_album = {'artist': artist, 'album title': album_title}
if music:
music_album['music'] = music
return music_album
album_dict = make_album('Radiohead', 'Pablo Honey')
print(album_dict)
album_dict = make_album('The Beatles', 'Rubber Soul')
print(album_dict)
album_dict = make_album('Gordon Lightfoot', 'Sundown')
print(album_dict)
album_dict = make_album('John Denver', 'Rocky Mountain High', music = '12')
print(album_dict)
{'artist': 'Radiohead', 'album title': 'Pablo Honey', 'music': '0'} {'artist': 'The Beatles', 'album title': 'Rubber Soul', 'music': '0'} {'artist': 'Gordon Lightfoot', 'album title': 'Sundown', 'music': '0'} {'artist': 'John Denver', 'album title': 'Rocky Mountain High', 'music': '12'}
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 user_makes_album(artist, album_title):
"""Return a dictionary for an album dictionary"""
music_album = {'artist': artist, 'album title': album_title}
return music_album
while True:
print('Give the name of the artist and the title the album')
print('Type "quit" when finished')
artist = input("Artist Name: ")
if artist == 'quit':
break
album = input("Name of Album: ")
if album == 'quit':
break
created_album = user_makes_album(artist, album)
print(f'{created_album}')
Give the name of the artist and the title the album Type "quit" when finished {'artist': 'john', 'album title': 'apple'} Give the name of the artist and the title the album Type "quit" when finished {'artist': 'john', 'album title': 'hellos'} Give the name of the artist and the title the album Type "quit" when finished {'artist': 'tupac', 'album title': 'grass'} Give the name of the artist and the title the album Type "quit" when finished {'artist': 'Hellos', 'album title': 'white'} Give the name of the artist and the title the album Type "quit" when finished
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(my_texts):
"""Displays text message"""
for text in my_texts:
txt = f'{text}'
print(txt)
the_texts = ['hello!', 'good morning', 'have a great day!']
show_messages(the_texts)
hello! good morning 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.
def send_messages(unsent, sent_messages):
"""Moves unsent messages to sent messages"""
while unsent:
sending = unsent.pop()
print(f'delivering... "{sending}"')
sent_messages.append(sending)
unsent = [input()]
sent_messages = []
send_messages(unsent, sent_messages)
print(unsent)
print(sent_messages)
delivering... "hello" [] ['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.
with open('texts/learning_python.txt') as file_object:
contents = file_object.read()
print(contents)
In Python you can print things In Python you can use the input function
filename = 'texts/learning_python.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
In Python you can print things In Python you can use the input function
facts = []
with open(filename) as file_object:
for line in file_object:
facts.append(line)
print(facts)
['In Python you can print things\n', 'In Python you can use the input function\n']
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(filename) as file_object:
lines = file_object.readlines()
for line in lines:
line = line.rstrip()
print(line.replace('Python', 'C'))
In C you can print things In C you can use the input function
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.
filename = 'texts/guest.txt'
with open(filename, 'w') as file_object:
file_object.write(input('what is your name? '))
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.
print('tell us your name and then enter "quit" when done')
while True:
name = input('\ntell us your name: ')
if name == 'quit':
break
else:
with open (filename, 'a') as file_object:
file_object.write(f'\n{name}')
print(f'thank you, {name}, for coming')
tell us your name and then enter "quit" when done thank you, jack, for coming
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 = 'texts/poll.txt'
reasons = []
while True:
reason = input('\nWhy do you like programming?')
reasons.append(reason)
end_poll = input('When you are finished giving reasons, type "done", otherwise hit enter.')
if end_poll == 'done':
break
with open (filename, 'a') as file_object:
for reason in reasons:
file_object.write(f'\n{reason}')
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:
x=input("Give me a number: ")
x=int(x)
y=input("Give me another number: ")
y=int(y)
except ValueError:
print("numbers only please")
else:
sum = x+y
print(f"The sum of your inputs is {str(sum)}.")
The sum of your inputs is 357.
try:
x=input("Give me a number: ")
x=int(x)
y=input("Give me another number: ")
y=int(y)
except ValueError:
print("numbers only please")
else:
sum = x+y
print(f"The sum of your inputs is {str(sum)}.")
numbers only please
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.
print('when finished type "done"')
while True:
try:
x = input('\ngive first number')
if x == 'done':
break
x = int(x)
y = input('give second number')
if y == 'done':
break
y = int(y)
except ValueError:
print('numbers only please')
else:
sum = x+y
print(f'the sum of your inputs is {str(sum)}.')
when finished type "done" the sum of your inputs is 111. numbers only please the sum of your inputs is 666.
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 = ['texts/cats.txt', 'texts/dogs.txt', 'cats.txt']
for filename in filenames:
print(f'\n{filename} contains: ')
try:
with open(filename) as f:
contents = f.read()
print(contents)
except FileNotFoundError:
print("This file does not exist")
texts/cats.txt contains: Zoe Zippy Zoopy texts/dogs.txt contains: Charger Ruff Todd cats.txt contains: This file does not exist
Question 29¶
Silent Cats and Dogs: Modify your except block in Question 28 to fail silently if either file is missing.
filenames = ['texts/cats.txt', 'texts/dogs.txt', 'cats.txt']
for filename in filenames:
print(f'\n{filename} contains: ')
try:
with open(filename) as f:
contents = f.read()
print(contents)
except:
pass
texts/cats.txt contains: Zoe Zippy Zoopy texts/dogs.txt contains: Charger Ruff Todd cats.txt contains:
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
def count_common_words(filename, word):
"""Count how many times word appears in the text."""
# Note: This is a really simple approximation, and the number returned
# will be higher than the actual count.
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
pass
else:
word_count = contents.count(word)
msg = f"'{word}' appears in {filename} about {word_count} times."
print(msg)
filename = 'texts/odds_ends.txt'
count_common_words(filename, 'the')
filename = 'texts/adventure.txt'
count_common_words(filename, 'the')
'the' appears in texts/odds_ends.txt about 4736 times. 'the' appears in texts/adventure.txt about 482 times.
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_common_words(filename, word):
"""Count how many times word appears in the text."""
# Note: This is a really simple approximation, and the number returned
# will be higher than the actual count.
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
pass
else:
word_count = contents.lower().count(word)
msg = f"'{word}' appears in {filename} about {word_count} times."
print(msg)
filename = 'texts/odds_ends.txt'
count_common_words(filename, 'the ')
filename = 'texts/adventure.txt'
count_common_words(filename, 'the ')
'the ' appears in texts/odds_ends.txt about 3354 times. 'the ' appears in texts/adventure.txt about 358 times.