Lab 4¶
from datetime import datetime
now = datetime.now()
print(f"Submitted time: {now}")
Submitted time: 2024-03-04 14:44:58.356780
Question 1¶
Personal Message: Use a variable to represent a person’s name, and print a message to that person. Your message should be simple, such as, “Hello Eric, would you like to learn some Python today?”
#person_name = input("Please enter your name: ")
person_name = "Lubna"
message = f"Hello {person_name}, would you like to learn some Python today?"
print(message)
Hello Lubna, would you like to learn some Python today?
Question 2¶
Name Cases: Use a variable to represent a person’s name, aaaaand then print that person’s name in lowercase, uppercase, and title case.
person_name = "Robin"
lowercase_name = person_name.lower()
uppercase_name = person_name.upper()
titlecase_name = person_name.title()
lowercase_name, uppercase_name, titlecase_name
('robin', 'ROBIN', 'Robin')
Question 3¶
Famous Quote: Find a quote from a famous person you admire. Print the quote and the name of its author. Your output should look something like the following, including the quotation marks:
Albert Einstein once said, “A person who never made a mistake never tried anything new.”
quote = "The only way to do great work is to love what you do."
author = "Steve Jobs"
formatted_quote = f'{author} once said, “{quote}”'
formatted_quote
'Steve Jobs once said, “The only way to do great work is to love what you do.”'
Question 4¶
Stripping Names: Use a variable to represent a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, "\t" and "\n", at least once. Print the name once, so the whitespace around the name is displayed. Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip().
person_name = " Eric Smith "
print(f"This is the person's name:{person_name}")
name_with_whitespace = f'Name with whitespace: "{person_name}"'
# to remove whitespace from the left
name_lstrip = f'After lstrip(): "{person_name.lstrip()}"'
# to remove whitespace from the right
name_rstrip = f'After rstrip(): "{person_name.rstrip()}"'
# to remove whitespace from both sides
name_strip = f'After strip(): "{person_name.strip()}"'
name_with_whitespace, name_lstrip, name_rstrip, name_strip
This is the person's name: Eric Smith
('Name with whitespace: " Eric Smith "',
'After lstrip(): "Eric Smith "',
'After rstrip(): " Eric Smith"',
'After strip(): "Eric Smith"')
Question 5¶
Names: Store the names of a few of your friends in a list called names. Print each person’s name by accessing each element in the list, one at a time.
Friends = ["Rachel", "Chandler", "Pheobe", "Monica", "Ross", "Joey"]
for name in Friends:
print(name)
Rachel Chandler Pheobe Monica Ross Joey
Question 6¶
Your Own List: Think of your favorite mode of transportation, such as a motorcycle or a car, and make a list that stores several examples. Use your list to print a series of statements about these items, such as “I would like to own a Honda motorcycle.”
transportation_modes = ["Tesla Model S", "BMW motorcycle", "Piper airplane"]
for i in transportation_modes:
print(f'I would like to own a {i}')
I would like to own a Tesla Model S I would like to own a BMW motorcycle I would like to own a Piper airplane
Question 7¶
Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza names in a list, and then use a for loop to print the name of each pizza.
Modify your for loop to print a sentence using the name of the pizza instead of printing just the name of the pizza. For each pizza you should have one line of output containing a simple statement like I like pepperoni pizza.
favorite_pizzas = ["Pepperoni", "Margherita", "Hawaiian"]
for pizza in favorite_pizzas:
print(pizza)
for pizza in favorite_pizzas:
print(f"My favorite pizza is: {pizza}")
print("I like pizzas, with a thin crispy crust!")
print("I really love pizza!")
Pepperoni Margherita Hawaiian My favorite pizza is: Pepperoni My favorite pizza is: Margherita My favorite pizza is: Hawaiian I like pizzas, with a thin crispy crust! I really love pizza!
Add a line at the end of your program, outside the for loop, that states how much you like pizza. The output should consist of three or more lines about the kinds of pizza you like and then an additional sentence, such as I really love pizza!
Question 8¶
Animals: Think of at least three different animals that have a common characteristic. Store the names of these animals in a list, and then use a for loop to print out the name of each animal.
Modify your program to print a statement about each animal, such as A dog would make a great pet.
pets = ["dog", "cat", "rabbit"]
for pet in pets:
print(pet)
for pet in pets:
print(f"A {pet} would make a great pet.")
dog cat rabbit A dog would make a great pet. A cat would make a great pet. A rabbit would make a great pet.
Add a line at the end of your program stating what these animals have in common. You could print a sentence such as Any of these animals would make a great pet!
pets = ["dog", "cat", "rabbit"]
for pet in pets:
print(pet)
for pet in pets:
print(f"A {pet} would make a great pet.")
print("Any of these animals are cute and can be a great pet!")
dog cat rabbit A dog would make a great pet. A cat would make a great pet. A rabbit would make a great pet. Any of these animals are cute and can be a great pet!
Question 9¶
Summing a Hundred: Make a list of the numbers from one to one hundred, and then use min() and max() to make sure your list actually starts at one and ends at one hundred. Also, use the sum() function to see how quickly Python can add a hundred numbers.
numbers=list(range(1,101))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
1 100 5050
Question 10¶
Odd Numbers: Use the third argument of the range() function to make a list of the odd numbers from 1 to 20. Use a for loop to print each number.
odd_numbers = list(range(1, 21, 2))
for number in odd_numbers:
print(number)
1 3 5 7 9 11 13 15 17 19
Question 11¶
Threes: Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the numbers in your list.
threes=list(range(3,31,3))
for i in threes:
print(i)
3 6 9 12 15 18 21 24 27 30
Question 12¶
Cube Comprehension: Use a list comprehension to generate a list of the first 10 cubes.
cubes = [x**3 for x in range(1, 11)]
print(cubes)
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Question 13¶
Slices: Using one of the programs you wrote in this lab, add several lines to the end of the program that do the following:
Print the message The first three items in the list are:. Then use a slice to print the first three items from that program’s list.
Friends = ["Rachel", "Chandler", "Pheobe", "Monica", "Ross", "Joey"]
print(Friends[:3])
['Rachel', 'Chandler', 'Pheobe']
Print the message Three items from the middle of the list are:. Use a slice to print three items from the middle of the list.
Friends = ["Rachel", "Chandler", "Pheobe", "Monica", "Ross", "Joey"]
print(Friends[1:4])
['Chandler', 'Pheobe', 'Monica']
Print the message The last three items in the list are:. Use a slice to print the last three items in the list.
print(Friends[-3:])
['Monica', 'Ross', 'Joey']
Question 14¶
Buffet: A buffet-style restaurant offers only five basic foods. Think of five simple foods, and store them in a tuple.
Use a for loop to print each food the restaurant offers.
foods = ("Pizza", "Burger", "Salad", "Kulfi", "Fries")
for food in foods:
print(food)
Pizza Burger Salad Kulfi Fries
The restaurant changes its menu, replacing two of the items with different foods. Add a line that rewrites the tuple, and then use a for loop to print each of the items on the revised menu.
# Changing two items in the original menu
# Since tuples are immutable, we'll convert it to a list, make changes, and convert it back to a tuple
buffet_foods_list = list(foods)
buffet_foods_list[1] = "Fish" # Replace "Burger" with "Fish"
buffet_foods_list[4] = "Pasta" # Replace "Fries" with "Pasta"
revised_buffet_foods = tuple(buffet_foods_list)
# Print each of the items on the revised menu using a for loop
print("Revised Buffet Menu:")
for food in revised_buffet_foods:
print(food)
Revised Buffet Menu: Pizza Fish Salad Kulfi Pasta
Question 15¶
Alien Colors: Imagine an alien was just shot down in a game. Create a variable called alien_color and assign it a value of green, yellow, or red.
- Write an if statement to test whether the alien’s color is green. If it is, print a message that the player just earned 5 points.
- Write one version of this program that passes the if test and another that fails. (The version that fails will have no output.)
# Version that passes the if test
alien_color = "green"
# If the alien's color is green, print a message
if alien_color == "green":
message_pass = "You just earned 5 points for shooting the alien!"
else:
message_pass = "You just lost 5 points for shooting the wrong alien!"
# Version that fails the if test
alien_color = "red"
# If the alien's color is green, print a message
if alien_color == "green":
message_fail = "You just earned 5 points for shooting the alien!"
else:
message_fail = "You just lost 5 points for shooting the wrong alien!"
message_pass, message_fail
('You just earned 5 points for shooting the alien!',
'You just lost 5 points for shooting the wrong alien!')
Question 16¶
Stages of Life: Write an if-elif-else chain that determines a person’s stage of life. Set a value for the variable age, and then:
- If the person is less than 2 years old, print a message that the person is a baby.
- If the person is at least 2 years old but less than 4, print a message that the person is a toddler.
- If the person is at least 4 years old but less than 13, print a message that the person is a kid.
- If the person is at least 13 years old but less than 20, print a message that the person is a teenager.
- If the person is at least 20 years old but less than 65, print a message that the person is an adult.
age = 25
if age < 2:
print("The person is a baby.")
elif age < 4:
print("The person is a toddler.")
elif age < 13:
print("The person is a kid.")
elif age < 20:
print("The person is a teenager.")
elif age < 65:
print("The person is an adult.")
else:
print("The person is a senior citizen.")
The person is an adult.
Question 17¶
Favorite Fruit: Make a list of your favorite fruits, and then write a series of independent if statements that check for certain fruits in your list.
- Make a list of your three favorite fruits and call it favorite_fruits.
- Write five if statements. Each should check whether a certain kind of fruit is in your list. If the fruit is in your list, the if block should print a statement, such as You really like bananas!
favorite_fruits = ['grapes', 'blackberries', 'strawberry']
if 'grapes' in favorite_fruits:
print("You really like grapes!")
if 'blackberries' in favorite_fruits:
print("You really like blackberries!")
if 'kiwi' in favorite_fruits:
print("You really like kiwis!")
if 'strawberry' in favorite_fruits:
print("You really like strawberries!")
if 'pineapple' in favorite_fruits:
print("You really like pineapples!")
You really like grapes! You really like blackberries! You really like strawberries!
Question 18¶
Hello Admin: Make a list of five or more usernames, including the name admin. Imagine you are writing code that will print a greeting to each user after they log in to a website. Loop through the list, and print a greeting to each user:
- If the username is 'admin', print a special greeting, such as Hello admin, would you like to see a status report?
- Otherwise, print a generic greeting, such as Hello Jaden, thank you for logging in again.
usernames = ['admin', 'jaden', 'emma', 'sam', 'chris', 'sophia']
for username in usernames:
if username == 'admin':
print("Hello admin, would you like to see a status report?")
else:
print(f"Hello {username.title()}, thank you for logging in again!")
Hello admin, would you like to see a status report? Hello Jaden, thank you for logging in again! Hello Emma, thank you for logging in again! Hello Sam, thank you for logging in again! Hello Chris, thank you for logging in again! Hello Sophia, thank you for logging in again!
Question 19¶
Checking Usernames: Do the following to create a program that simulates how websites ensure that everyone has a unique username.
- Make a list of five or more usernames called
current_users. - Make another list of five usernames called
new_users. Make sure one or two of the new usernames are also in thecurrent_userslist. - Loop through the
new_userslist to see if each new username has already been used. If it has, print a message that the person will need to enter a new username. If a username has not been used, print a message saying that the username is available. - Make sure your comparison is case insensitive. If 'John' has been used, 'JOHN' should not be accepted. (To do this, you’ll need to make a copy of
current_userscontaining the lowercase versions of all existing users.)
current_users = ["Rachel", "Chandler", "Pheobe", "Monica", "Ross", "Joey"]
new_users = ["Nagel", "Emma", "Rachel", "Chandler", "Pheobe", "Monica", "Ross", "joey", "Ellis"]
current_users_lower = [user.lower() for user in current_users]
for new_user in new_users:
if new_user.lower() in current_users_lower:
print(f"Sorry, the username '{new_user}' is already taken. Please enter a new username.")
else:
print(f"The username '{new_user}' is available.")
The username 'Nagel' is available. The username 'Emma' is available. Sorry, the username 'Rachel' is already taken. Please enter a new username. Sorry, the username 'Chandler' is already taken. Please enter a new username. Sorry, the username 'Pheobe' is already taken. Please enter a new username. Sorry, the username 'Monica' is already taken. Please enter a new username. Sorry, the username 'Ross' is already taken. Please enter a new username. Sorry, the username 'joey' is already taken. Please enter a new username. The username 'Ellis' is available.
Question 20¶
Ordinal Numbers: Ordinal numbers indicate their position in a list, such as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.
- Store the numbers 1 through 9 in a list.
- Loop through the list.
- Use an
if-elif-elsechain inside the loop to print the proper ordinal ending for each number. Your output should read "1st 2nd 3rd 4th 5th 6th 7th 8th 9th", and each result should be on a separate line.
numbers = list(range(1, 10))
for number in numbers:
if number == 1:
ordinal = '1st'
elif number == 2:
ordinal = '2nd'
elif number == 3:
ordinal = '3rd'
else:
ordinal = f'{number}th'
print(ordinal)
1st 2nd 3rd 4th 5th 6th 7th 8th 9th