Lab 5¶
Submission instructions¶
- Download the notebook from https://whkim15.github.io/spatialtsp/
- 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.
# Define a dictionary with person's information
person_info = {
"first_name": "Wanhee",
"last_name": "Kim",
"age": 31,
"city": "Knoxville"
}
# Print each piece of information
for key, value in person_info.items():
print(f"{key.title()}: {value}")
First_Name: Wanhee Last_Name: Kim Age: 31 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 = {
'Amy': 7,
'Joyce': 13,
'Bob': 22,
'Tom': 9,
'Annie': 3
}
for name, number in favorite_numbers.items():
print(f"{name}'s favorite number is {number}")
Amy's favorite number is 7 Joyce's favorite number is 13 Bob's favorite number is 22 Tom's favorite number is 9 Annie'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 = {
'for': 'A control flow statement for specifying iteration, which allows code to be executed repeatedly.',
'if': 'A conditional statement that executes a set of statements if a given condition is true.',
'loop': 'The action of doing something over and over again.',
'variables': 'Symbols that are used to store data values.',
'list': 'A data structure in Python that is a mutable, or changeable, ordered sequence of elements.'
}
for term, meaning in glossary.items():
print(f"{term}:\n\t{meaning}")
for: A control flow statement for specifying iteration, which allows code to be executed repeatedly. if: A conditional statement that executes a set of statements if a given condition is true. loop: The action of doing something over and over again. variables: Symbols that are used to store data values. list: A data structure in Python that is a mutable, or changeable, ordered sequence of elements.
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.
revised_terms = {
'string': 'A sequence of characters.',
'integer': 'A whole number without a fractional part.',
'float': 'A number that has a decimal point.',
'boolean': 'A data type that can hold one of two possible values: True or False.',
'conditional': 'Statements that perform different computations or actions depending on whether a condition evaluates to true or false.'
}
glossary.update(revised_terms)
for term, meaning in glossary.items():
print(f"{term}:\n\t{meaning}")
for: A control flow statement for specifying iteration, which allows code to be executed repeatedly. if: A conditional statement that executes a set of statements if a given condition is true. loop: The action of doing something over and over again. variables: Symbols that are used to store data values. list: A data structure in Python that is a mutable, or changeable, ordered sequence of elements. string: A sequence of characters. integer: A whole number without a fractional part. float: A number that has a decimal point. boolean: A data type that can hold one of two possible values: True or False. conditional: Statements that perform different computations or actions depending on whether a condition evaluates to true or false.
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',
'Han': 'Korea',
'Tennessee': 'USA'
}
for river, country in rivers.items():
print(f"The {river} runs through {country}.")
print("\nThe following rivers are included:")
for river in rivers.keys():
print(river)
print("\nThese rivers run through the following countries:")
for country in rivers.values():
print(country)
The Nile runs through Egypt. The Han runs through Korea. The Tennessee runs through USA. The following rivers are included: Nile Han Tennessee These rivers run through the following countries: Egypt Korea USA
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 = {
'Knoxville': {'country': 'USA', 'population': '187,500', 'fact': 'Home to the University of Tennessee'},
'Seoul': {'country': 'South Korea', 'population': '9.7 million', 'fact': 'Home to the Seoul National University'},
'Beijing': {'country': 'China', 'population': '21 million', 'fact': 'Home to the Peking University'}
}
for city, info in cities.items():
print(f"\n{city}:")
for key, value in info.items():
print(f" {key.title()}: {value}")
Knoxville: Country: USA Population: 187,500 Fact: Home to the University of Tennessee Seoul: Country: South Korea Population: 9.7 million Fact: Home to the Seoul National University Beijing: Country: China Population: 21 million Fact: Home to the Peking University
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.”
def rental_car_request(car_type):
return f"Let me see if I can find you a {car_type}."
example_car_type = "Genesis"
rental_car_message = rental_car_request(example_car_type)
print("\n" + rental_car_message)
Let me see if I can find you a Genesis.
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.
def check_table(group_size):
if group_size > 8:
return "You’ll have to wait for a table."
else:
return "Your table is ready."
# Example usage of the function:
restaurant_seating_message_1 = check_table(10)
restaurant_seating_message_2 = check_table(6)
print(restaurant_seating_message_1)
print(restaurant_seating_message_2)
You’ll have to wait for a table. Your table is ready.
Question 9¶
Multiples of Ten: Ask the user for a number, and then report whether the number is a multiple of 10 or not.
def is_multiple_of_ten(number):
return number % 10 == 0
# Example usage of the function:
is_ten_multiple_1 = is_multiple_of_ten(20)
is_ten_multiple_2 = is_multiple_of_ten(23)
print(is_ten_multiple_1)
print(is_ten_multiple_2)
True False
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.
def add_toppings():
toppings = []
while True:
topping = input(f"Enter a topping for your pizza (type 'quit' to finish): ")
if topping == 'quit':
break
toppings.append(topping)
print(f"I'll add {topping} to your pizza.")
return toppings
# write the toppings for the function:
add_toppings()
I'll add corn to your pizza. I'll add ham to your pizza. I'll add bacon to your pizza.
['corn', 'ham', '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("I'm learning about functions, loops, and conditionals in this chapter")
learning_message = display_message()
print(learning_message)
I'm learning about functions, loops, and conditionals in this chapter None
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}.")
request_book='Harry Potter'
favorite_book(request_book)
One of my favorite books is Harry Potter.
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 text printed on it is '{message}'.")
make_shirt('Medium', 'Go Vols!')
make_shirt(size='Small', message='Tennessee.')
The size of the shirt is Medium and the text printed on it is 'Go Vols!'. The size of the shirt is Small and the text printed on it is 'Tennessee.'.
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.'):
print(f"The size of the shirt is {size} and the text printed on it is '{message}'.")
make_shirt() # This will use the default values.
make_shirt(size='Small', message='I love GEOG510!')
The size of the shirt is Large and the text printed on it is 'I love Python.'. The size of the shirt is Small and the text printed on it is 'I love GEOG510!'.
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('Seoul', country='South Korea')
describe_city('Knoxville', country='USA')
Reykjavik is in Iceland. Seoul is in South Korea. Knoxville is in USA.
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('Knoxville', 'USA'))
print(city_country('Seoul', 'South Korea'))
print(city_country('Beijing', 'China'))
Knoxville, USA Seoul, South Korea Beijing, 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, 'album': album_title}
if number_of_songs:
album['number_of_songs'] = number_of_songs
return album
print(make_album('Beyonce', 'Album1'))
print(make_album('Michael Jackson', 'Album2', number_of_songs=10))
print(make_album('Prince', 'Album3'))
{'artist': 'Beyonce', 'album': 'Album1'}
{'artist': 'Michael Jackson', 'album': 'Album2', 'number_of_songs': 10}
{'artist': 'Prince', 'album': 'Album3'}
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.
# Re_Define question17
def make_album(artist_name, album_title, number_of_songs=None):
album = {'artist': artist_name, 'album': album_title}
if number_of_songs:
album['number_of_songs'] = number_of_songs
return album
# Initialize an empty list to store albums
user_albums = []
# Simulated user inputs
while True:
artist = input("Enter artist name (or 'quit' to finish): ").strip() # Added 'strip function' to quit simulator easily
if artist.lower() == 'quit':
break
title = input("Enter album title: ")
songs = input("Enter number of songs (or leave blank if unknown): ")
songs = int(songs) if songs.isdigit() else None
album = make_album(artist, title, songs)
user_albums.append(album)
# Print the list of user albums
for album in user_albums:
print(album)
{'artist': 'prince', 'album': 'beautiful girl', 'number_of_songs': 14}
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!", "My name is Wanhee Kim", "How are you?"]
show_messages(messages)
Hello! My name is Wanhee Kim How are 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.
messages = ["Hello!", "My name is Wanhee Kim", "How are you?"]
sent_messages=[]
def send_messages(messages):
while messages:
current_message = messages.pop()
print(f"Sending message: {current_message}")
sent_messages.append(current_message)
send_messages(messages[:])
print("Original messages:", messages)
print("Sent messages:", sent_messages)
Sending message: How are you? Sending message: My name is Wanhee Kim Sending message: Hello! Original messages: ['Hello!', 'My name is Wanhee Kim', 'How are you?'] Sent messages: ['How are you?', 'My name is Wanhee Kim', '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.
text = """In Python you can. Store information in variables.
In Python you can. Write functions to perform tasks.
In Python you can. Loop through lists."""
# entire file
print(text)
# looping over the file object
for line in text.split('\n'):
print(line)
# storing the lines in a list & working outside with block
lines = text.split('\n')
for line in lines:
print(line)
In Python you can. Store information in variables. In Python you can. Write functions to perform tasks. In Python you can. Loop through lists. In Python you can. Store information in variables. In Python you can. Write functions to perform tasks. In Python you can. Loop through lists. In Python you can. Store information in variables. In Python you can. Write functions to perform tasks. In Python you can. Loop through lists.
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.
message = ("I live in Nashville, USA.\n"
"I am phd Student at University of Tennessee Nashville.")
print(message)
modified_contents = message.replace('Nashville', 'Knoxville')
print(modified_contents)
I live in Nashville, USA. I am phd Student at University of Tennessee Nashville. I live in Knoxville, USA. I am phd Student at University of Tennessee Knoxville.
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.
# Define writing txt
def write_guest_name(filename, guest_name):
with open(filename, 'a') as f:
f.write(guest_name + "\n")
#add_guest
input_name = "Wanhee"
def add_guest():
print(f"What's your name?")
guest_name = input_name
# Write to guest.txt file
print(f"Hello, {guest_name}! Your name has been added to the guest book.")
return guest_name
# Call the add_guest function and simulate writing to a file
guest_name = add_guest()
#write_guest_name(f'D:/GIS program/Github/geog510/exercise/guest.txt', guest_name)
What's your name? Hello, Wanhee! Your name has been added to the guest book.
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.
guest_name = ["Dr.Wu", "Dr.Hyun", "Mr.Wanhee"]
def add_to_guest_book():
booked_names = guest_name
for names in booked_names:
print(f"Hello, {names}! Your name has been added to the guest book.")
# Call the add_to_guest_book function to simulate the guest book process
add_to_guest_book()
Hello, Dr.Wu! Your name has been added to the guest book. Hello, Dr.Hyun! Your name has been added to the guest book. Hello, Mr.Wanhee! Your name has been added to the guest book.
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_file = 'C:\\Users\\dooco\\OneDrive\\5. Doctoral Degree\\1. Class\\8. GEOG510\\responses.txt'
with open(reasons_file, 'a') as file:
while True:
reason = input("Why do you like programming? (type 'quit' to end) ")
if reason == 'quit':
break
file.write(reason + "\n")
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():
try:
x = int(a)
y = int(b)
sum = x + y
except ValueError:
print("Please enter a valid number.")
else:
print(f"The sum of {x} and {y} is {sum}.")
(a,b) =(10, 5)
add_numbers()
(a,b) =(10, "data")
add_numbers()
The sum of 10 and 5 is 15. Please enter a valid number.
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.
def add_numbers(a, b):
try:
x = int(a)
y = int(b)
return x + y
except ValueError:
print("Please enter a valid number.")
return None
while True:
first_number = input("Enter first number (or 'quit' to finish): ")
if first_number.lower() == 'quit':
break
second_number = input("Enter second number: ")
result = add_numbers(first_number, second_number)
if result is not None:
print(f"The sum of {first_number} and {second_number} is {result}.")
The sum of 10 and 5 is 15. The sum of 13 and 245 is 258.
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.
def print_file_contents(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
print_file_contents(f'D:/GIS program/Github/geog510/exercise/cats.txt')
print_file_contents(f'D:/GIS program/Github/geog510/exercise/dogs.txt')
#print_file_contents(f'D:/GIS program/Github/geog510/exercise/rabbits.txt')
Sorry, the file D:/GIS program/Github/geog510/exercise/cats.txt does not exist. Sorry, the file D:/GIS program/Github/geog510/exercise/dogs.txt does not exist.
Question 29¶
Silent Cats and Dogs: Modify your except block in Question 28 to fail silently if either file is missing.
def print_file_contents_silently(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except FileNotFoundError:
pass
print_file_contents_silently(f'D:/GIS program/Github/geog510/exercise/cats.txt')
print_file_contents_silently(f'D:/GIS program/Github/geog510/exercise/dogs.txt')
#print_file_contents_silently(f'D:/GIS program/Github/geog510/exercise/rabbits.txt')
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 requests
# URL of the text file
url = 'https://gutenberg.org/cache/epub/73159/pg73159.txt'
# Send a GET request to the URL
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
# Read the content of the file
text = response.text.lower() # Convert text to lowercase
# Words to count
words_to_count = ['the', 'then', 'there']
# Dictionary to store the counts
word_counts = {word: text.count(f' {word} ') for word in words_to_count}
# Print the counts
for word, count in word_counts.items():
print(f"The word '{word}' appears {count} times in the text.")
else:
print("Failed to retrieve the text file.")
The word 'the' appears 11607 times in the text. The word 'then' appears 122 times in the text. The word 'there' appears 255 times in the text.