Lab 4¶
Submission instructions¶
- Download the notebook from https://geosdemo.gishub.org/labs/lab4
- 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-05-11 17:53:34.334414
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?”
print("Hello my friend how is Python today")
Hello my friend how is Python today
Question 2¶
Name Cases: Use a variable to represent a person’s name, and then print that person’s name in lowercase, uppercase, and title case.
x = "richard"
print(x.lower())
print(x.upper())
print(x.title())
richard RICHARD Richard
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.”
print('Marcus Aurelius once said, "The happiness of your life depends upon the quality of your thoughts"')
Marcus Aurelius once said, "The happiness of your life depends upon the quality of your thoughts"
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().
x = "\tPeter\nStug "
print(x)
Peter Stug
print(x.strip())
Peter Stug
print(x.lstrip())
Peter Stug
print(x.rstrip())
Peter Stug
#==to strip()
print((x.lstrip()).rstrip())
Peter Stug
print((x.strip()).replace("\n"," "))
Peter Stug
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.
names = ["Peter", "Rocky", "Trick"]
print(names[0])
print(names[1])
print(names[2])
Peter Rocky Trick
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.”
modes_t = ["Motorcycle", "Ferrari", "Private plane", "Yate"]
print(f"I would like to own a {modes_t[1]}")
print(f"I would like to own a {modes_t[3]}")
I would like to own a Ferrari I would like to own a Yate
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.
pizzas = ["margerita", "Hawai", "pesto"]
for pizza in pizzas:
print(f"I like {pizza.title()} pizza!")
I like Margerita pizza! I like Hawai pizza! I like Pesto 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!
for pizza in pizzas:
print(f"I like {pizza.title()} pizza!")
print("\tI really love pizza")
I like Margerita pizza! I like Hawai pizza! I like Pesto pizza! 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.
animal_names = ["Terry", "Larry", "Jac"]
for name in animal_names:
print(f"{name} would make a great pet.")
Terry would make a great pet. Larry would make a great pet. Jac 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!
animal_names = ["Terry", "Larry", "Jac"]
for name in animal_names:
print(f"{name} would make a great pet.")
print("These animals have in common the tail.")
Terry would make a great pet. Larry would make a great pet. Jac would make a great pet. These animals have in common the tail.
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.
list_num = list(range(1, 101))
print(min(list_num))
print(max(list_num))
print(sum(list_num))
1 100 5050
i = 0
c = 0
while i <= 100:
c = c + i
i += 1
print(c)
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.
l = []
for i in range(1,20,2):
l.append(i)
print(l)
[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.
l = []
l = [i*3 for i in range(1,100) if i * 3 <= 30]
print(l)
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
#Chatgpt
l = []
for i in range(3, 31):
if i % 3 == 0:
l.append(i)
print(l)
[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.
l = [ i ** 3 for i in range(1,11)]
print(l)
[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.
modes_t = ["Motorcycle", "Ferrari", "Private plane", "Yate", "Bike"]
print(f"I would like to own a {modes_t[1]}")
print(f"I would like to own a {modes_t[3]}")
print("\nThe first three items in the list are:")
for mode in modes_t[0:3]:
print(f"\t- {mode}")
I would like to own a Ferrari I would like to own a Yate The first three items in the list are: - Motorcycle - Ferrari - Private plane
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.
print("\nMiddle items in the list are:")
for mode in modes_t[2:]:
print(f"\t- {mode}")
Middle items in the list are: - Private plane - Yate - Bike
Print the message The last three items in the list are:. Use a slice to print the last three items in the list.
print("\nLast items in the list are:")
for mode in modes_t[-2:]:
print(f"\t- {mode}")
Last items in the list are: - Yate - Bike
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.
basic_food = ("Rice", "Meat", 'Salad', 'Soup', 'Pizza')
for meal in basic_food:
print(meal)
Rice Meat Salad Soup Pizza
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.
basic_food = ("Rice", "Meat", 'Salad', 'Soup', 'Pizza')
l = list(basic_food)
l[1] = "meat"
l[4] = "Burger"
for i in l:
print(i)
Rice meat Salad Soup Burger
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.)
alien_colour = "yellow"
if alien_colour == "green":
print("You just earned 5 points")
else:
pass
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 = int(input("Please insert an age: "))
if age < 2:
print("It is a baby.")
elif age < 4:
print("It is a Toddler")
elif age < 13:
print("It is a kid")
elif age < 20:
print('It is a teenager')
elif age < 65:
print('It is an adult')
else:
print('Free')
--------------------------------------------------------------------------- StdinNotImplementedError Traceback (most recent call last) Cell In[30], line 1 ----> 1 age = int(input("Please insert an age: ")) 3 if age < 2: 4 print("It is a baby.") File ~/.local/lib/python3.9/site-packages/ipykernel/kernelbase.py:1190, in Kernel.raw_input(self, prompt) 1188 if not self._allow_stdin: 1189 msg = "raw_input was called, but this frontend does not support input requests." -> 1190 raise StdinNotImplementedError(msg) 1191 return self._input_request( 1192 str(prompt), 1193 self._parent_ident["shell"], 1194 self.get_parent("shell"), 1195 password=False, 1196 ) StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
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!
l = ['pera', ' fresa', 'manzana', 'naranja', 'durazno']
favorite_fruits = ['manzana', 'naranja','kiwi']
for favorite_f in favorite_fruits:
if favorite_f in l:
print(f'You really like {favorite_f}')
else:
print(f'No record of {favorite_f}')
You really like manzana You really like naranja No record of kiwi
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.
l_names = ['Terry', 'larry', 'admin', 'Luca', 'Lucy']
for name in l_names:
if name == 'admin':
print('Hello admin would you like to see the report')
else:
print(f'Hello {name}, thank you for logging again')
Hello Terry, thank you for logging again Hello larry, thank you for logging again Hello admin would you like to see the report Hello Luca, thank you for logging again Hello Lucy, thank you for logging 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_users
list. - Loop through the
new_users
list 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_users
containing the lowercase versions of all existing users.)
current_users = ['Terry', 'Larry', 'Admin', 'Luca', 'Lucy']
new_users = ['Peter', 'Terry', 'Jack', 'Claud', 'Lucy']
current_users_lower = [current_user.lower() for current_user in current_users]
for new_user in new_users:
if new_user.lower() in current_users_lower:
print(f'{new_user} has already been used, insert a new name.')
else:
print(f'{new_user} is available.')
Peter is available. Terry has already been used, insert a new name. Jack is available. Claud is available. Lucy has already been used, insert a new name.
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-else
chain 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 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers_str = [str(number) for number in numbers]
num_strs = []
for num in numbers_str:
if num == "1":
num_strs.append(num + 'st')
elif num == '2':
num_strs.append(num + 'nd')
elif num == '3':
num_strs.append(num + 'rd')
else:
num_strs.append(num + 'th')
for num_str in num_strs:
print(num_str)
1st 2nd 3rd 4th 5th 6th 7th 8th 9th
#alternative chat gpt
numbers = list(range(1, 10))
for num in numbers:
if num == 1:
print(f"{num}st")
elif num == 2:
print(f"{num}nd")
elif num == 3:
print(f"{num}rd")
else:
print(f"{num}th")
1st 2nd 3rd 4th 5th 6th 7th 8th 9th