Chapter Questions Flashcards

1
Q

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.”

A

print(‘Albert Einstein once said, “A person who never made a mistake’)
print(‘never tried anything new.”’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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().

A

name = “\tEric Matthes\n”

print(“Unmodified:”)
print(name)

print(“\nUsing lstrip():”)
print(name.lstrip())

print(“\nUsing rstrip():”)
print(name.rstrip())

print(“\nUsing strip():”)
print(name.strip())

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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.

A

names = [‘ron’, ‘tyler’, ‘dani’]

print(names[0])
print(names[1])
print(names[2])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Start with the list you used in Exercise 3-1, but instead of just printing each person’s name, print a message to them. The text of each message should be the same, but each message should be personalized with the person’s name.

A

names = [‘ron’, ‘tyler’, ‘dani’]

msg = f”Hello, {names[0].title()}!”
print(msg)

msg = f”Hello, {names[1].title()}!”
print(msg)

msg = f”Hello, {names[2].title()}!”
print(msg)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

If you could invite anyone, living or deceased, to dinner, who would you invite? Make a list that includes at least three people you’d like to invite to dinner. Then use your list to print a message to each person, inviting them to dinner.

A

guests = [‘guido van rossum’, ‘jack turner’, ‘lynn hill’]

name = guests[0].title()
print(f”{name}, please come to dinner.”)

name = guests[1].title()
print(f”{name}, please come to dinner.”)

name = guests[2].title()
print(f”{name}, please come to dinner.”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

You just heard that one of your guests can’t make the dinner, so you need to send out a new set of invitations. You’ll have to think of someone else to invite.

Start with your program from Exercise 3-4. Add a print statement at the end of your program stating the name of the guest who can’t make it.
Modify your list, replacing the name of the guest who can’t make it with the name of the new person you are inviting.
Print a second set of invitation messages, one for each person who is still in your list.

A
# Invite some people to dinner.
guests = ['guido van rossum', 'jack turner', 'lynn hill']

name = guests[0].title()
print(f”{name}, please come to dinner.”)

name = guests[1].title()
print(f”{name}, please come to dinner.”)

name = guests[2].title()
print(f”{name}, please come to dinner.”)

name = guests[1].title()
print(f”\nSorry, {name} can’t make it to dinner.”)

# Jack can't make it! Let's invite Gary instead.
del(guests[1])
guests.insert(1, 'gary snyder')
# Print the invitations again.
name = guests[0].title()
print(f"\n{name}, please come to dinner.")

name = guests[1].title()
print(f”{name}, please come to dinner.”)

name = guests[2].title()
print(f”{name}, please come to dinner.”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

You just found a bigger dinner table, so now more space is available. Think of three more guests to invite to dinner.

Start with your program from Exercise 3-4 or Exercise 3-5. Add a print statement to the end of your program informing people that you found a bigger dinner table.
Use insert() to add one new guest to the beginning of your list.
Use insert() to add one new guest to the middle of your list.
Use append() to add one new guest to the end of your list. Print a new set of invitation messages, one for each person in your list.
A
# Invite some people to dinner.
guests = ['guido van rossum', 'jack turner', 'lynn hill']

name = guests[0].title()
print(f”{name}, please come to dinner.”)

name = guests[1].title()
print(f”{name}, please come to dinner.”)

name = guests[2].title()
print(f”{name}, please come to dinner.”)

name = guests[1].title()
print(f”\nSorry, {name} can’t make it to dinner.”)

# Jack can't make it! Let's invite Gary instead.
del(guests[1])
guests.insert(1, 'gary snyder')
# Print the invitations again.
name = guests[0].title()
print(f"\n{name}, please come to dinner.")

name = guests[1].title()
print(f”{name}, please come to dinner.”)

name = guests[2].title()
print(f”{name}, please come to dinner.”)

# We got a bigger table, so let's add some more people to the list.
print("\nWe got a bigger table!")
guests.insert(0, 'frida kahlo')
guests.insert(2, 'reinhold messner')
guests.append('elizabeth peratrovich')

name = guests[0].title()
print(f”{name}, please come to dinner.”)

name = guests[1].title()
print(f”{name}, please come to dinner.”)

name = guests[2].title()
print(f”{name}, please come to dinner.”)

name = guests[3].title()
print(f”{name}, please come to dinner.”)

name = guests[4].title()
print(f”{name}, please come to dinner.”)

name = guests[5].title()
print(f”{name}, please come to dinner.”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

You just found out that your new dinner table won’t arrive in time for the dinner, and you have space for only two guests.

Start with your program from Exercise 3-6. Add a new line that prints a message saying that you can invite only two people for dinner.
Use pop() to remove guests from your list one at a time until only two names remain in your list. Each time you pop a name from your list, print a message to that person letting them know you’re sorry you can’t invite them to dinner.
Print a message to each of the two people still on your list, letting them know they’re still invited.
Use del to remove the last two names from your list, so you have an empty list. Print your list to make sure you actually have an empty list at the end of your program.
A
# Invite some people to dinner.
guests = ['guido van rossum', 'jack turner', 'lynn hill']

name = guests[0].title()
print(f”{name}, please come to dinner.”)

name = guests[1].title()
print(f”{name}, please come to dinner.”)

name = guests[2].title()
print(f”{name}, please come to dinner.”)

name = guests[1].title()
print(f”\nSorry, {name} can’t make it to dinner.”)

# Jack can't make it! Let's invite Gary instead.
del(guests[1])
guests.insert(1, 'gary snyder')
# Print the invitations again.
name = guests[0].title()
print(f"\n{name}, please come to dinner.")

name = guests[1].title()
print(f”{name}, please come to dinner.”)

name = guests[2].title()
print(f”{name}, please come to dinner.”)

# We got a bigger table, so let's add some more people to the list.
print("\nWe got a bigger table!")
guests.insert(0, 'frida kahlo')
guests.insert(2, 'reinhold messner')
guests.append('elizabeth peratrovich')

name = guests[0].title()
print(f”{name}, please come to dinner.”)

name = guests[1].title()
print(f”{name}, please come to dinner.”)

name = guests[2].title()
print(f”{name}, please come to dinner.”)

name = guests[3].title()
print(f”{name}, please come to dinner.”)

name = guests[4].title()
print(f”{name}, please come to dinner.”)

name = guests[5].title()
print(f”{name}, please come to dinner.”)

# Oh no, the table won't arrive on time!
print("\nSorry, we can only invite two people to dinner.")

name = guests.pop()
print(f”Sorry, {name.title()} there’s no room at the table.”)

name = guests.pop()
print(f”Sorry, {name.title()} there’s no room at the table.”)

name = guests.pop()
print(f”Sorry, {name.title()} there’s no room at the table.”)

name = guests.pop()
print(f”Sorry, {name.title()} there’s no room at the table.”)

# There should be two people left. Let's invite them.
name = guests[0].title()
print(f"{name}, please come to dinner.")

name = guests[1].title()
print(f”{name}, please come to dinner.”)

# Empty out the list.
del(guests[0])
del(guests[0])
# Prove the list is empty.
print(guests)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Think of at least five places in the world you’d like to visit.

Store the locations in a list. Make sure the list is not in alphabetical order.
Print your list in its original order. Don’t worry about printing the list neatly, just print it as a raw Python list.
Use sorted() to print your list in alphabetical order without modifying the actual list.
Show that your list is still in its original order by printing it.
Use sorted() to print your list in reverse alphabetical order without changing the order of the original list.
Show that your list is still in its original order by printing it again.
Use reverse() to change the order of your list. Print the list to show that its order has changed.
Use reverse() to change the order of your list again. Print the list to show it’s back to its original order.
Use sort() to change your list so it’s stored in alphabetical order. Print the list to show that its order has been changed.
Use sort() to change your list so it’s stored in reverse alphabetical order. Print the list to show that its order has changed.
A

locations = [‘himalaya’, ‘andes’, ‘tierra del fuego’, ‘labrador’, ‘guam’]

print(“Original order:”)
print(locations)

print(“\nAlphabetical:”)
print(sorted(locations))

print(“\nOriginal order:”)
print(locations)

print(“\nReverse alphabetical:”)
print(sorted(locations, reverse=True))

print(“\nOriginal order:”)
print(locations)

print(“\nReversed:”)
locations.reverse()
print(locations)

print(“\nOriginal order:”)
locations.reverse()
print(locations)

print(“\nAlphabetical”)
locations.sort()
print(locations)

print(“\nReverse alphabetical”)
locations.sort(reverse=True)
print(locations)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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.
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!

A

favorite_pizzas = [‘pepperoni’, ‘hawaiian’, ‘veggie’]

# Print the names of all the pizzas.
for pizza in favorite_pizzas:
    print(pizza)

print(“\n”)

# Print a sentence about each pizza.
for pizza in favorite_pizzas:
    print(f"I really love {pizza} pizza!")

print(“\nI really love pizza!”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

A number raised to the third power is called a cube. For example, the cube of 2 is written as 2**3 in Python. Make a list of the first 10 cubes (that is, the cube of each integer from 1 through 10), and use a for loop to print out the value of each cube.

A

cubes = []
for number in range(1, 11):
cube = number**3
cubes.append(cube)

for cube in cubes:
print(cube)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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

A

odd_numbers = list(range(1, 30, 2))
for value in odd_numbers:
print(value)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Start with your program from Exercise 4-1 (page 60). Make a copy of the list of pizzas, and call it friend_pizzas. Then, do the following:

Add a new pizza to the original list.
Add a different pizza to the list friend_pizzas.
Prove that you have two separate lists. Print the message, My favorite pizzas are:, and then use a for loop to print the first list. Print the message, My friend’s favorite pizzas are:, and then use a for loop to print the second list. Make sure each new pizza is stored in the appropriate list.

A
favorite_pizzas = ['pepperoni', 'hawaiian', 'veggie']
friend_pizzas = favorite_pizzas[:]

favorite_pizzas.append(“meat lover’s”)
friend_pizzas.append(‘pesto’)

print(“My favorite pizzas are:”)
for pizza in favorite_pizzas:
print(f”- {pizza}”)

print(“\nMy friend’s favorite pizzas are:”)
for pizza in friend_pizzas:
print(f”- {pizza}”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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.
Try to modify one of the items, and make sure that Python rejects the change.
The restaurant changes its menu, replacing two of the items with different foods. Add a block of code that rewrites the tuple, and then use a for loop to print each of the items on the revised menu.

A

menu_items = (
‘rockfish sandwich’, ‘halibut nuggets’, ‘smoked salmon chowder’,
‘salmon burger’, ‘crab cakes’,
)

print(“You can choose from the following menu items:”)
for item in menu_items:
print(f”- {item}”)

menu_items = (
‘rockfish sandwich’, ‘halibut nuggets’, ‘smoked salmon chowder’,
‘black cod tips’, ‘king crab legs’,
)

print(“\nOur menu has been updated.”)
print(“You can now choose from the following items:”)
for item in menu_items:
print(f”- {item}”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Make a list of the numbers from one to one million, and then use min() and max() to make sure your list actually starts at one and ends at one million. Also, use the sum() function to see how quickly Python can add a million numbers.

A

numbers = list(range(1, 1_000_001))

print(min(numbers))
print(max(numbers))
print(sum(numbers))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

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 tha fails. (The version that fails will have no output.)

A

alien_color = ‘green’

if alien_color == ‘green’:
print(“You just earned 5 points!”)

17
Q

Choose a color for an alien as you did in Exercise 5-3, and write an if-else chain.

If the alien’s color is green, print a statement that the player just earned 5 points for shooting the alien.
If the alien’s color isn’t green, print a statement that the player just earned 10 points.
Write one version of this program that runs the if block and another that runs the else block.

A

alien_color = ‘green’

if alien_color == ‘green’:
print(“You just earned 5 points!”)
else:
print(“You just earned 10 points!”)

18
Q

Turn your if-else chain from Exercise 5-4 into an if-elif-else cahin.

If the alien is green, print a message that the player earned 5 points.
If the alien is yellow, print a message that the player earned 10 points.
If the alien is red, print a message that the player earned 15 points.
Write three versions of this program, making sure each message is printed for the appropriate color alien.

A

alien_color = ‘red’

if alien_color == 'green':
    print("You just earned 5 points!")
elif alien_color == 'yellow':
    print("You just earned 10 points!")
else:
    print("You just earned 15 points!")
19
Q

Write an if-elif-else cahin 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 toddler.
If the person is at least 13 years old but less than 20, print a message that the person is a toddler.
If the person is at least 20 years old but less than 65, print a message that the person is a toddler.
If the person is age 65 or older, print a message that the person is an elder.

A

age = 17

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!")
20
Q

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!

A

favorite_fruits = [‘blueberries’, ‘salmonberries’, ‘peaches’]

if 'bananas' in favorite_fruits:
    print("You really like bananas!")
if 'apples' in favorite_fruits:
    print("You really like apples!")
if 'blueberries' in favorite_fruits:
    print("You really like blueberries!")
if 'kiwis' in favorite_fruits:
    print("You really like kiwis!")
if 'peaches' in favorite_fruits:
    print("You really like peaches!")
21
Q
  1. 8: make a list of five or more usernames, including the name ‘admin’. imagine you are writing code that will print agreeing to each user after they log into a website. loop through the list and print a greeting to each.
    - if the user is ‘admin’, print a special greeting
    - otherwise print a generic greeting
A

usernames = [‘eric’, ‘willie’, ‘admin’, ‘erin’, ‘ever’]

for username in usernames:
if username == ‘admin’:
print(“Hello admin, would you like to see a status report?”)
else:
print(f”Hello {username}, thank you for loggin in again!”)

22
Q

Use the pizza example to create multiple lists and check if the items in one list are in the other list . use if-else statement to print out answers if an item is and isn’t in a list

A

available_toppings = [‘mushrooms’, ‘olives’, ‘pepperoni’, ‘pineapple’,’extra cheese’, ‘green peppers’]

requested_toppings = [‘mushrooms’, ‘french fries’, ‘extra cheese’]
for value in requested_toppings:
if value in available_toppings:
print(f”adding {value} to the pizza.”)
else:
print(f”sorry we don’t have any {value}”)

23
Q

Add an if test to hello_admin.py to make sure the list of users is not empty.

If the list is emtpy, print the message We need to find some users!
Remove all of the usernames from your list, and make sure the correct message is printed.

A

usernames = []

if usernames:
    for username in usernames:
        if username == 'admin':
            print("Hello admin, would you like to see a status report?")
        else:
            print(f"Hello {username}, thank you for loggin in again!")
else:
    print("We need to find some users!")
24
Q

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 the current_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.

A
current_users = ['eric', 'willie', 'admin', 'erin', 'Ever']
new_users = ['sarah', 'Willie', 'PHIL', 'ever', 'Iona']

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}, that name is taken.”)
else:
print(f”Great, {new_user} is still available.”)

25
Q

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.

A

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")