Lab 5¶
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.
# Create a dictionary to store information about a person
person_info = {
"first_name": "Abidur",
"last_name": "Reza",
"age": 96,
"city": "Dhaka"
}
# Print each piece of information stored in the dictionary
for key, value in person_info.items():
print(f"{key}: {value}")
first_name: Abidur last_name: Reza age: 96 city: Dhaka
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.
# Create a dictionary to store people's favorite numbers
favorite_numbers = {
"Robin": 5,
"Daina": 42,
"Shayma": 23,
"Diana": 9,
"Evan": 13
}
# Print each person's name and their favorite number
for name, number in favorite_numbers.items():
print(f"{name}'s favorite number is {number}")
Robin's favorite number is 5 Daina's favorite number is 42 Shayma's favorite number is 23 Diana's favorite number is 9 Evan'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": "A storage location paired with an associated symbolic name, which contains some known or unknown quantity of information referred to as a value.",
"loop": "A programming construct that repeats a block of code multiple times until a certain condition is met.",
"function": "A block of organized, reusable code that is used to perform a single, related action.",
"dictionary": "A collection of key-value pairs, where each key is unique and is used to store and retrieve data.",
"list": "A collection of items in a particular order. Lists can contain items of different types."
}
# Print each word and its meaning in a neatly formatted output
for term, definition in glossary.items():
print(f"{term}:\n {definition}\n")
variable:
A storage location paired with an associated symbolic name, which contains some known or unknown quantity of information referred to as a value.
loop:
A programming construct that repeats a block of code multiple times until a certain condition is met.
function:
A block of organized, reusable code that is used to perform a single, related action.
dictionary:
A collection of key-value pairs, where each key is unique and is used to store and retrieve data.
list:
A collection of items in a particular order. Lists can contain items of different types.
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.
# Adding five more Python terms to the glossary
glossary.update({
"function": "A named block of code that is designed to do one specific job.",
"argument": "A piece of information that is passed from a function call to a function.",
"conditional statement": "A statement that controls the flow of execution depending on some condition.",
"module": "A file containing a set of functions and variables that you can include in your applications.",
"tuple": "An immutable list, meaning you can't change its values."
})
# Loop through the dictionary and print each term and its definition
for term, definition in glossary.items():
print(f"{term}:\n {definition}\n")
variable: A storage location paired with an associated symbolic name, which contains some known or unknown quantity of information referred to as a value. loop: A programming construct that repeats a block of code multiple times until a certain condition is met. function: A named block of code that is designed to do one specific job. dictionary: A collection of key-value pairs, where each key is unique and is used to store and retrieve data. list: A collection of items in a particular order. Lists can contain items of different types. argument: A piece of information that is passed from a function call to a function. conditional statement: A statement that controls the flow of execution depending on some condition. module: A file containing a set of functions and variables that you can include in your applications. tuple: An immutable list, meaning you can't change its values.
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",
"padma": "bangladesh"
}
for river, country in rivers.items():
print(f"The {river.title()} runs through {country.title()}.")
print("\nRivers mentioned:")
for river in rivers.keys():
print(river.title())
print("\nCountries mentioned:")
for country in rivers.values():
print(country.title())
The Nile runs through Egypt. The Amazon runs through Brazil. The Padma runs through Bangladesh. Rivers mentioned: Nile Amazon Padma Countries mentioned: Egypt Brazil 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.
# Dictionary of cities, each containing a dictionary of information about the city
cities = {
"new york": {
"country": "United States",
"population": "8.4 million",
"fact": "Home to the Statue of Liberty."
},
"paris": {
"country": "France",
"population": "2.1 million",
"fact": "Known as the City of Light."
},
"tokyo": {
"country": "Japan",
"population": "13.9 million",
"fact": "Has the most Michelin stars of any city in the world."
}
}
# Loop to print the name of each city and all the information stored about it
for city, info in cities.items():
print(f"{city.title()}:")
for key, value in info.items():
print(f" {key.title()}: {value}")
print() # Adding a blank line for better readability between cities
New York: Country: United States Population: 8.4 million Fact: Home to the Statue of Liberty. Paris: Country: France Population: 2.1 million Fact: Known as the City of Light. Tokyo: Country: Japan Population: 13.9 million Fact: Has the most Michelin stars of any city in the world.
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.”
user_input = input("What kind of rental car would you like? ")
print(f"Let me see if I can find you a {user_input}.")
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.
num_people = int(input("How many people are in your dinner group? "))
if num_people > 8:
print("I'm sorry, you'll have to wait for a table.")
else:
print("Your table is ready. Enjoy your meal!")
Your table is ready. Enjoy your meal!
Question 9¶
Multiples of Ten: Ask the user for a number, and then report whether the number is a multiple of 10 or not.
user_number = int(input("Enter a number: "))
if user_number % 10 == 0:
print(f"{user_number} is a multiple of 10.")
else:
print(f"{user_number} is not a multiple of 10.")
67 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("Enter a pizza topping (type 'quit' to finish): ")
if topping.lower() == 'quit':
break
pizza_toppings.append(topping)
print(f"Adding {topping} to your pizza.")
if pizza_toppings:
print("\nYour pizza will have the following toppings:")
for topping in pizza_toppings:
print("- " + topping)
else:
print("You didn't choose any toppings for your pizza.")
Adding Olives to your pizza. Adding Extra Cheese to your pizza. Adding Basil to your pizza. Adding Mashroom to your pizza. Your pizza will have the following toppings: - Olives - Extra Cheese - Basil - Mashroom
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 functions and how they can be used to organize and reuse code.")
display_message()
In this chapter, I am learning about functions and how they can be used to organize and reuse code.
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("Strength Finder 2.0")
One of my favorite books is Strength Finder 2.0.
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.
# Define the function make_shirt with two parameters: size and message
def make_shirt(size, message):
print(f"Making a {size} t-shirt with the message: '{message}'")
# Call the function with positional arguments
make_shirt('medium', 'Python Rocks!')
# Call the function with keyword arguments
make_shirt(message='Code More, Worry Less', size='large')
Making a medium t-shirt with the message: 'Python Rocks!' Making a large 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.
# Modify the function make_shirt to have default values for size and message
def make_shirt(size='large', message='I love Python'):
print(f"Making a {size} t-shirt with the message: '{message}'")
# Make a large shirt with the default message
make_shirt()
# Make a medium shirt with the default message
make_shirt(size='medium')
# Make a shirt of any size with a different message
make_shirt(size='small', message='Code is Poetry')
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: 'Code is Poetry'
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.
# Define the function describe_city with a default value for the country parameter
def describe_city(city, country='Bangladesh'):
print(f"{city} is in {country}.")
# Call the function for three different cities, with at least one not in the default country
describe_city('Khulna')
describe_city('Dhaka', 'Bangladesh')
describe_city('Tokyo', 'Japan')
Khulna is in Bangladesh. Dhaka is in Bangladesh. 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.
# Define the function city_country that takes in the name of a city and its country
def city_country(city, country):
return f"{city}, {country}"
# Call the function with three city-country pairs and print the values returned
print(city_country('Santiago', 'Chile'))
print(city_country('Dhaka', 'Bangladesh'))
print(city_country('Copenhagen', 'Denmark'))
Santiago, Chile Dhaka, Bangladesh Copenhagen, Denmark
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.
# Define the function make_album with an optional parameter for the number of songs
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
# Use the function to make three dictionaries representing different albums
album1 = make_album('The Beatles', 'Abbey Road')
album2 = make_album('Led Zeppelin', 'Led Zeppelin IV')
album3 = make_album('Pink Floyd', 'The Dark Side of the Moon')
# Print each return value
print(album1)
print(album2)
print(album3)
# Make at least one new function call that includes the number of songs on an album
album4 = make_album('Nirvana', 'Nevermind', number_of_songs=12)
print(album4)
album5 = make_album('LinkinPark', 'A Thousand Suns', 16)
print(album5)
{'artist': 'The Beatles', 'album': 'Abbey Road'}
{'artist': 'Led Zeppelin', 'album': 'Led Zeppelin IV'}
{'artist': 'Pink Floyd', 'album': 'The Dark Side of the Moon'}
{'artist': 'Nirvana', 'album': 'Nevermind', 'songs': 12}
{'artist': 'LinkinPark', 'album': 'A Thousand Suns', 'songs': 16}
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, title):
if artist and title:
album = {'artist': artist, 'title': title}
return album
else:
print("Invalid input. Both artist and title must be provided.")
while True:
artist_input = input("Enter the artist (type 'quit' to exit): ")
if artist_input.lower() == 'quit':
break
title_input = input("Enter the album title: ")
if title_input.lower() == 'quit':
break
album_dict = make_album(artist_input, title_input)
if album_dict:
print(album_dict)
{'artist': 'LinkinPark', 'title': 'Living Things'}
{'artist': 'LinkinPark', 'title': 'One More Light'}
{'artist': 'LinkinPark ', 'title': 'Minuites To Midnight'}
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.
# Define the function show_messages that prints each text message from a list
def show_messages(messages):
for message in messages:
print(message)
# List of short text messages
messages = ["Hello, how are you?", "Today is a great day!", "Python is fun.", "Keep learning!"]
# Pass the list to the function
show_messages(messages)
Hello, how are you? Today is a great day! Python is fun. Keep learning!
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 show_messages(messages):
for message in messages:
print(message)
def send_messages(messages, sent_messages):
while messages:
current_message = messages.pop(0)
print(f"Sending message: {current_message}")
sent_messages.append(current_message)
text_messages = [
"Hello, how are you?", "Today is a great day!", "Python is fun.", "Keep learning!"
]
sent_messages = []
send_messages(text_messages, sent_messages)
print("Original Messages:")
show_messages(text_messages)
print("\nSent Messages:")
show_messages(sent_messages)
Sending message: Hello, how are you? Sending message: Today is a great day! Sending message: Python is fun. Sending message: Keep learning! Original Messages: Sent Messages: Hello, how are you? Today is a great day! Python is fun. Keep learning!
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', 'r') as file:
content = file.read()
print("Reading the entire file:")
print(content)
with open('learning_python.txt', 'r') as file:
print("\nLooping over the file object:")
for line in file:
print(line.strip())
with open('learning_python.txt', 'r') as file:
lines = file.readlines()
print("\nWorking with lines outside the with block:")
for line in lines:
print(line.strip())
Reading the entire file: 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 files to save data and user inputs. 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 files to save data and user inputs. Working with 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 files to save data and user inputs.
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:
lines = file.readlines()
modified_lines = []
for line in lines:
modified_line = line.replace('Python', 'Java Script')
modified_lines.append(modified_line)
print("\nModified lines (replacing 'python' with 'Java Script'):")
for modified_line in modified_lines:
print(modified_line.strip())
Modified lines (replacing 'python' with 'Java Script'): In Java Script, you can create variables to store information. In Java Script, you can use loops to perform repetitive tasks efficiently. In Java Script, you can use functions to organize your code into reusable blocks. In Java Script, you can work with files to save data and user inputs.
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 = input("Please enter your name: ")
with open('guest.txt', 'w') as file:
file.write(user_name)
print(f"Thank you, {user_name}! Your name has been added to guest.txt.")
Thank you, Mahnaz! Your name has been added 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:
user_name = input("Please enter your name (type 'quit' to exit): ")
if user_name.lower() == 'quit':
break
print(f"Welcome, {user_name}!")
with open(filename, 'a') as file:
file.write(f"{user_name}\n")
print("Thank you for visiting! Your entries have been recorded in guest_book.txt.")
Welcome, Mahnaz! Welcome, Sarker! Welcome, Meem! Welcome, qquit! Thank you for visiting! Your entries have been recorded in guest_book.txt.
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 = 'user_response.txt'
while True:
user_response = input("Why do you like programming? (type 'quit' to exit): ")
if user_response.lower() == 'quit':
break
with open(filename, 'a') as file:
file.write(f"{user_response}\n")
print("Thank you for sharing your reasons! The responses have been recorded in user_response.txt.")
Thank you for sharing your reasons! The responses have been recorded in user_response.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.
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 + num2
print(f"The sum of {num1} and {num2} is: {result}")
except ValueError:
print("Error: Please enter valid number.")
The sum of 5.0 and 9.0 is: 14.0
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:
user_input = input("Enter the first number (type 'quit' to exit): ")
if user_input.lower() == 'quit':
break
num1 = float(user_input)
num2 = float(input("Enter the second number: "))
result = num1 + num2
print(f"The sum of {num1} and {num2} is: {result}")
except ValueError:
print("Error: Please enter valid number.")
Error: Please enter valid number. The sum of 5.0 and 3.0 is: 8.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 cats_file:
cats_content = cats_file.read()
print("Contents of cats.txt:")
print(cats_content)
except FileNotFoundError as e:
print(f"Error reading cats.txt: {e}")
try:
with open('dogs.txt', 'r') as dogs_file:
dogs_content = dogs_file.read()
print("\nContents of dogs.txt:")
print(dogs_content)
except FileNotFoundError as e:
print(f"Error reading dogs.txt: {e}")
Contents of cats.txt: Whiskers Mittens Shadow Contents of dogs.txt: Husky Biscuit Marble
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("Contents 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: Whiskers Mittens Shadow Contents of dogs.txt: Husky Biscuit Marble
Question 30¶
Common Words: Visit Project Gutenberg (https://gutenberg.org/) and find a few texts you’d like to analyze. Download the text files for these works, or copy the raw text from your browser into a text file on your computer. You can use the count() method to find out how many times a word or phrase appears in a string. For example, the following code counts the number of times 'row' appears in a string:
line = "Row, row, row your boat"
line.count("row")
2
line.lower().count("row")
3
Notice that converting the string to lowercase using lower() catches all appearances of the word you’re looking for, regardless of how it’s formatted.
Write a program that reads the files you found at Project Gutenberg and determines how many times the word the appears in each text. This will be an approximation because it will also count words such as then and there. Try counting the, with a space in the string, and see how much lower your count is.
def count_word_occurrences(file_path, word):
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
word_count = content.count(word)
word_count_case_insensitive = content.lower().count(word.lower())
print(f"Occurrences of '{word}' (case-sensitive): {word_count}")
print(f"Occurrences of '{word}' (case-insensitive): {word_count_case_insensitive}")
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
count_word_occurrences(r'moral_teachings.txt', 'the ')
count_word_occurrences(r'moral_teachings.txt', 'the')
Occurrences of 'the ' (case-sensitive): 1669 Occurrences of 'the ' (case-insensitive): 1898 Occurrences of 'the' (case-sensitive): 2478 Occurrences of 'the' (case-insensitive): 2821