『Pythonプログラミング-入門から実践まで』第7、8章練習問題選練


7-1. 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.”
知識点分析:Python入力関数inputの簡単な応用
コード:
#7-1
brand = input('What kind of car do you like to rent?
') print("Let me see if I can find you a "+brand)

7-3. Multiples of Ten: Ask the user for a number, and then report whether the number is a multiple of 10 or not.
ナレッジポイント分析:練習、%演算子の入力
コード:
#7-3
num = input('please enter an integer
') divisible = True if int(num) % 10 == 0 else False if divisible: print(num+" is a multiple of 10") else: print(num+" is NOT a multiple of 10")

7-5. Movie Tickets: A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket.
7-6. Three Exits: Write different versions of either Exercise 7-4 or Exercise 7-5 that do each of the following at least once:
• Use a conditional test in the while statement to stop the loop.
• Use an active variable to control how long the loop runs.
• Use a break statement to exit the loop when the user enters a 'quit' value.
インテリジェントポイント分析:ユーザー入力インタラクションとwhileループ
コード:
#7-5&7-6

#solution 1
age = input("Please enter your age('quit' to exit)
") while age != 'quit': if int(age) < 3: print("free") elif 3 <= int(age) <= 12: #this form is acceptable print("$10") else: print("$15") age = input("Please enter your age('quit' to exit)
") #solution 2 active = True while active: age = input("Please enter your age('quit' to exit)
") if age == 'quit': active = False elif int(age) < 3: print("free") elif 3 <= int(age) <= 12: #this form is acceptable print("$10") else: print("$15") #solution 3 while True: age = input("Please enter your age('quit' to exit)
") if age == 'quit': break elif int(age) < 3: print("free") elif 3 <= int(age) <= 12: #this form is acceptable print("$10") else: print("$15")

7-8. Deli: Make a list called sandwich_orders and fill it with the names of various sandwiches. Then make an empty list called finished_sandwiches. Loop through the list of sandwich orders and print a message for each order, such as I made your tuna sandwich. As each sandwich is made, move it to the list of finished sandwiches. After all the sandwiches have been made, print a message listing each sandwich that was made.
7-9. No Pastrami: Using the list sandwich_orders from Exercise 7-8, make sure the sandwich 'pastrami' appears in the list at least three times. Add code near the beginning of your program to print a message saying the deli has run out of pastrami, and then use a while loop to remove all occurrences of 'pastrami' from sandwich_orders. Make sure no pastrami sandwiches end up in finished_sandwiches.
インテリジェントポイント分析:リストにwhileループを適用するリストにwhileループを適用する:移動&削除
コード:
#7-8&7-9
sandwich_orders = ['tuna', 'pastrami', 'egg', 'pastrami', 'vegetables', 'Ham', 'pastrami']
finished_sandwiches = []

print("Sorry to inform you that pastrami has been sold out")
while 'pastrami' in sandwich_orders:
    sandwich_orders.remove('pastrami')

while sandwich_orders:
    sandwich = sandwich_orders.pop()
    finished_sandwiches.append(sandwich)
    print("I made your "+sandwich+" sandwich.")
print(finished_sandwiches)

if 'pastrami' not in finished_sandwiches:
    print("No pastrami sandwich was made")

8-5. 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.
ナレッジポイント分析ナレッジポイント分析:関数のパラメータ伝達とパラメータデフォルト
コード:
#8-5
def describe_city(city, country='china'):
    print(city.title() + ' is in ' + country.title())
    
describe_city('guangzhou')
describe_city('beijing')
describe_city(city='new york', country='america')

8-7. 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.
Add an optional parameter to make_album() that allows you to store the number of tracks on an album. If the calling line includes a value for the number of tracks, add that value to the album's dictionary. Make at least one new function call that includes the number of tracks on an album.
ナレッジポイント分析:関数に返される辞書およびオプションパラメータの実装
コード:
#8-7
def make_album(artist, name, count=-1):
    if count == -1:
        return {'artist':artist, 'name':name}
    else:
        return {'artist':artist, 'name':name, 'count':count}

album1 = make_album('alice', 'album1')
album2 = make_album('bob', 'album2', 10)
album3 = make_album('carol', 'album3')
print(album1, album2, album3) #notice

8-9. Magicians: Make a list of magician’s names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.
8-10. Great Magicians: Start with a copy of your program from Exercise 8-9. Write a function called make_great() that modifies the list of magicians by adding the phrase the Great to each magician’s name. Call show_magicians() to
see that the list has actually been modified.
8-11. Unchanged Magicians: Start with your work from Exercise 8-10. Call the function make_great() with a copy of the list of magicians’ names. Because the original list will be unchanged, return the new list and store it in a separate list. Call show_magicians() with each list to show that you have one list of the original names and one list with the Great added to each magician’s name.
Knowledge Point Analysis Knowledge Point Analysis:関数内のリストの変更(内部が外部に影響を及ぼす可能性があります)カンスウノウホウカンスウノリストノヘンコウ
コード:
#8-9&8-10&8-11
def show_magicians(magicians):
    for magician in magicians:
        print(magician.title())
        
def make_great(magicians):
    #magicians = ['the Great ' + magician for magician in magicians] #NOTE: here magicians becomes a new variable
    length = len(magicians)
    while length:
        magicians[length - 1] = 'the great ' + magicians[length - 1]
        length -= 1
    return magicians
    
magicians = ['alice', 'bob', 'carol', 'denis']
show_magicians(magicians)
make_great(magicians)
show_magicians(magicians)

magicians = ['alice', 'bob', 'carol', 'denis']
modifiedMagicians = make_great(magicians[:])
show_magicians(magicians)
show_magicians(modifiedMagicians)

8-12. Sandwiches: Write a function that accepts a list of items a person wants on a sandwich. The function should have one parameter that collects as many items as the function call provides, and it should print a summary of the sandwich that is being ordered. Call the function three times, using a different number of arguments each time.
ナレッジポイント分析:関数の任意の数の実パラメータ伝達
コード:
#8-12
def print_sandwich(*items):
    for item in items:
        print(item)
    print()

print_sandwich('egg')
print_sandwich('cucumber', 'egg', 'tomatoes')
print_sandwich('pork', 'bacon', 'vegetables', 'egg')

8-14. Cars: Write a function that stores information about a car in a dictionary. The function should always receive a manufacturer and a model name. It should then accept an arbitrary number of keyword arguments. Call the function
with the required information and two other name-value pairs, such as a color or an optional feature. Your function should work for a call like this one:
    
car = make_car('subaru', 'outback', color='blue', tow_package=True)
Print the dictionary that’s returned to make sure all the information was stored correctly.
ナレッジポイント分析:関数の任意の数のキーワードの実パラメータ伝達
コード:
#8-14
def make_car(manufacturer, name, **info):
    info['manufacturer'] = manufacturer
    info['name'] = name 
    return info

car = make_car('toyota', 'corolla', color='silver', displacement='1.8L')
print(car)