Lab-4¶
from datetime import datetime
now = datetime.now()
print(f"Submitted time: {now}")
Submitted time: 2024-03-07 21:23:51.001050
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 = "Bekub"
print(f"Hello {person_name}, you have no future.")
Hello Bekub, you have no future.
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.
person_name = "Codliver Shakib"
print(f"Lowercase: {person_name.lower()}")
print(f"Uppercase: {person_name.upper()}")
print(f"Title Case: {person_name.title()}")
Lowercase: codliver shakib Uppercase: CODLIVER SHAKIB Title Case: Codliver Shakib
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.”
Professor_Snape = "After all these time? Always"
print(f"Professor Snape replied to Professor Dumbledor question as, \"{Professor_Snape}\"")
Professor Snape replied to Professor Dumbledor question as, "After all these time? Always"
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 =" Shabiha \t Hossain \nMajor:\tGeography \t "
print(f"Original Name: '{person_name}'")
print(f"lstrip(): '{person_name.lstrip()}'")
print(f"rstrip(): '{person_name.rstrip()}'")
print(f"strip(): '{person_name.strip()}'")
Original Name: ' Shabiha Hossain Major: Geography ' lstrip(): 'Shabiha Hossain Major: Geography ' rstrip(): ' Shabiha Hossain Major: Geography' strip(): 'Shabiha Hossain Major: Geography'
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 = ['Maisha','Tanbi', 'Sraboni']
print(Names[0])
print(Names[1])
print(Names[2])
Maisha Tanbi Sraboni
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.”
Vehicles=['car', 'bike', 'train', 'bicycle']
print('I would like to travel by', Vehicles[2])
print('But one day I wish to buy a Tesla', Vehicles[0])
I would like to travel by train But one day I wish to buy a Tesla car
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.
pizza=['pepperoni', 'mushroom', 'chicken alfredo', 'deep dish']
for i in pizza:
print(i)
pepperoni mushroom chicken alfredo deep dish
verb=['hate', 'kinda like','love','absolutely love']
for verb, pizza in zip(verb,pizza):
print("I", verb, pizza, "pizza")
I hate pepperoni pizza I kinda like mushroom pizza I love chicken alfredo pizza I absolutely love deep dish 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!
pizza=['pepperoni', 'mushroom', 'chicken alfredo', 'deep dish']
verb=['hate', 'kinda like','love','absolutely love']
Message='I can never get bored of eating pizza. My kind of adrenaline.'
for verb, pizza in zip(verb,pizza):
print("I", verb, pizza, "pizza")
print(Message)
I hate pepperoni pizza I kinda like mushroom pizza I love chicken alfredo pizza I absolutely love deep dish pizza I can never get bored of eating pizza. My kind of adrenaline.
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.
animals=['dog', 'cat', 'bird', 'rabbit']
for i in animals:print(i)
dog cat bird rabbit
Line=['fluffy','cute','sweet','adorable']
for Line, animals in zip(Line,animals):
print(animals,"is", Line)
dog is fluffy cat is cute bird is sweet rabbit is adorable
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!
animals=['dog', 'cat', 'bird', 'rabbit']
Line=['fluffy','cute','sweet','adorable']
for Line, animals in zip(Line,animals):
print(animals,"is", Line,"and they are all designed to obey humans.")
dog is fluffy and they are all designed to obey humans. cat is cute and they are all designed to obey humans. bird is sweet and they are all designed to obey humans. rabbit is adorable and they are all designed to obey humans.
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.
Num=list(range(1,101))
print(min(Num), max(Num))
1 100
print(sum(Num))
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.
start = 1
end = 20
if start % 2 != 0:
for num in range(start, end + 1, 2):
print(num, end=" ")
else:
for num in range(start+1, end + 1, 2):
print(num, end=" ")
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 = [i for i in range(3, 30) if i % 3 == 0]
print(Threes)
[3, 6, 9, 12, 15, 18, 21, 24, 27]
Question 12¶
Cube Comprehension: Use a list comprehension to generate a list of the first 10 cubes.
Z = [number**3 for number in range(1,11)]
for T in Z:
print(T)
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.
pizza=['pepperoni', 'mushroom', 'chicken alfredo', 'deep dish', 'sausage', 'seafood', 'shrimp']
print('The first three items in the list are:', (pizza[:3]))
The first three items in the list are: ['pepperoni', 'mushroom', 'chicken alfredo']
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.
middle_start = len(pizza) // 2 - 1
middle_end = middle_start + 3
print('The three items from the middle in the list are:', (pizza[middle_start:middle_end]))
The three items from the middle in the list are: ['chicken alfredo', 'deep dish', 'sausage']
Print the message The last three items in the list are:. Use a slice to print the last three items in the list.
print('The last three items in the list are:', (pizza[-3:]))
The last three items in the list are: ['sausage', 'seafood', 'shrimp']
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.
Our_foods = (
'pasta', 'chowmein', 'curry','mousse', 'lemonade',
)
print("Our menu offers:")
for food in Our_foods:
print(f"- {food}")
Our menu offers: - pasta - chowmein - curry - mousse - lemonade
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.
Revised_foods = (
'vegetables', 'chowmein', 'chicken curry','mousse', 'lemonade',
)
print("Little change in our menu has been authorized.")
print("\nOur revised menu offers now:")
for food in Revised_foods:
print(f"- {food}")
Little change in our menu has been authorized. Our revised menu offers now: - vegetables - chowmein - chicken curry - mousse - lemonade
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_color = 'green'
if alien_color == 'green':
print("You just earned 5 points!")
You just earned 5 points!
alien_color = 'red'
if alien_color == 'green':
print("You just earned 5 points!")
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 = 21
if age < 2:
print("You're a baby")
elif age < 4:
print("You're a toddler")
elif age < 13:
print("You're a kid")
elif age < 20:
print("You're a teenager")
elif age < 65:
print("You're an adult")
else:
print("You're an elder")
You're 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 = ['mangoes', 'bananas', 'oranges']
if 'bananas' in favorite_fruits:
print("You really like bananas!")
if 'apples' in favorite_fruits:
print("You really like apples!")
else:
print("apples are not your fav!")
if 'oranges' in favorite_fruits:
print("You really like oranges!")
if 'blueberries' in favorite_fruits:
print("You really like blueberries!")
else:
print("blueberries are not your fav!")
if 'mangoes' in favorite_fruits:
print("You really like mangoes!")
You really like bananas! apples are not your fav! You really like oranges! blueberries are not your fav! You really like mangoes!
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.
username =['admin', 'meem', 'nazifa', 'max','lucas']
for name in username:
if name =='admin':
print('Hello admin, would you like to see a status report?')
else:
print(f"Hello {name}, thank you for logging in again!")
Hello admin, would you like to see a status report? Hello meem, thank you for logging in again! Hello nazifa, thank you for logging in again! Hello max, thank you for logging in again! Hello lucas, 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 =['admin', 'meem', 'nazifa', 'max','lucas']
new_users=['matt', 'Nazifa', 'Jeff', 'ken', 'MAX']
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 {new_user}, the name is taken.")
else:
print(f"Great, {new_user} is available.")
Great, matt is available. Sorry Nazifa, the name is taken. Great, Jeff is available. Great, ken is available. Sorry MAX, the name is taken.
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:
print("1st")
elif number == 2:
print("2nd")
elif number == 3:
print("3rd")
else:
print(f"{number}th")
1st 2nd 3rd 4th 5th 6th 7th 8th 9th