Chapter 7
本章主要学习用户输入和while循环,包括input()函数和while循环控制用户输入退出,处理列表和字典
Q 7-2 餐馆订位 : 编写一个程序,询问用户有多少人用餐。 如果超过8人,就打印一条消息,指出没有空桌;否则指出有空桌。
知识点:input()函数
代码:
#7-2
coustomer_number = int(input("How many people are in your dinner group?\n"))
if coustomer_number>8:
print("Sorry, you may wait for a table.")
else:
print("Ok, your table is ready.")
运行结果:
How many people are in your dinner group?
5
Ok, your table is ready.
Q 7-5 电影票 : 有家电影院根据观众的年龄收取不同的票价: 不到3岁的观众免费; 3~12岁的观众为10美元; 超过12岁的观众为15美元。 请编写一个循环, 在其中询问用户的年龄, 并指出其票价。
知识点:while控制退出
代码:
#7-5
prompt = "\nPlease tell me your age, and I'll tell you your ticket price.\n"
prompt += "Enter 'q' to end up asking.\n"
while True:
age = input(prompt)
if age=='q':
break
else:
age = int(age)
if age<3:
print("Your ticket is free.")
elif age>12:
print("Your ticket is $15.")
else:
print("Your ticket is $10.")
运行结果:
Please tell me your age, and I'll tell you your ticket price.
Enter 'q' to end up asking.
2
Your ticket is free.
Please tell me your age, and I'll tell you your ticket price.
Enter 'q' to end up asking.
9
Your ticket is $10.
Please tell me your age, and I'll tell you your ticket price.
Enter 'q' to end up asking.
20
Your ticket is $15.
Please tell me your age, and I'll tell you your ticket price.
Enter 'q' to end up asking.
q
Q 7-8 熟食店 : 创建一个名为sandwich_orders 的列表, 在其中包含各种三明治的名字; 再创建一个名为finished_sandwiches 的空列表。 遍历列表sandwich_orders , 对于其中的每种三明治, 都打印一条消息, 如I made your tuna sandwich , 并将其移到列表finished_sandwiches 。 所有三明 治都制作好后, 打印一条消息, 将这些三明治列出来。
Q 7-9 五香烟熏牛肉(pastrami) 卖完了 : 使用为完成练习7-8而创建的列表sandwich_orders , 并确保'pastrami' 在其中至少出现了三次。 在程序开头附近添加这样的代码: 打印一条消息, 指出熟食店的五香烟熏牛肉卖完了; 再使用一个while 循环将列表sandwich_orders 中的'pastrami' 都删除。 确认最终的列表finished_sandwiches 中不包含'pastrami' 。
知识点:while循环处理列表或字典。
代码:
#7-8,7-9
print("Deli has run out of pastrami.\n")
sandwich_orders = ['tuna','pastrami','bacon','pastrami','pastrami']
finished_sandwiches = []
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
while sandwich_orders:
finished = sandwich_orders.pop()
finished_sandwiches.append(finished)
print("I made your " + finished +" sandwiches.")
print("\nThe following users have been confirmed:")
for sandwiches in finished_sandwiches:
print(sandwiches.title()+" sandwiches")
运行结果:
Deli has run out of pastrami.
I made your bacon sandwiches.
I made your tuna sandwiches.
Chapter 8
本章主要学习函数编写,传递参数,将函数存储于模块中。
Q 8-3 T恤 : 编写一个名为make_shirt() 的函数, 它接受一个尺码以及要印到T恤上的字样。 这个函数应打印一个句子, 概要地说明T恤的尺码和字样。使用位置实参调用这个函数来制作一件T恤; 再使用关键字实参来调用这个函数。
Q 8-4 大号T恤 : 修改函数make_shirt() , 使其在默认情况下制作一件印有字样“I love Python”的大号T恤。 调用这个函数来制作如下T恤: 一件印有默认字样的大号T恤、 一件印有默认字样的中号T恤和一件印有其他字样的T恤(尺码无关紧要)。
知识点:编写,修改,调用函数
代码:
#8-3,8-4
def make_shirt(size = 'large', message = "I love Python"):
print("The size of the shirt is " + size + " and the message on it is " + message +".")
make_shirt('small' , 'Monday')
make_shirt(message = 'Monday', size='small')
make_shirt()
make_shirt('large')
make_shirt('medium')
make_shirt('small','Day')
运行结果:
The size of the shirt is small and the message on it is Monday.
The size of the shirt is small and the message on it is Monday.
The size of the shirt is large and the message on it is I love Python.
The size of the shirt is large and the message on it is I love Python.
The size of the shirt is medium and the message on it is I love Python.
The size of the shirt is small and the message on it is Day.
Q 8-7 专辑 : 编写一个名为make_album() 的函数, 它创建一个描述音乐专辑的字典。 这个函数应接受歌手的名字和专辑名, 并返回一个包含这两项信息的字典。 使用这个函数创建三个表示不同专辑的字典, 并打印每个返回的值, 以核实字典正确地存储了专辑的信息。给函数make_album() 添加一个可选形参, 以便能够存储专辑包含的歌曲数。 如果调用这个函数时指定了歌曲数, 就将这个值添加到表示专辑的字典中。 调用这个函数, 并至少在一次调用中指定专辑包含的歌曲数。
Q 8-8 用户的专辑 : 在为完成练习8-7编写的程序中, 编写一个while 循环, 让用户输入一个专辑的歌手和名称。 获取这些信息后, 使用它们来调用函数数make_album() , 并将创建的字典打印出来。 在这个while 循环中, 务必要提供退出途径。
知识点:函数返回值
代码:
#8-7,8-8
def make_album(artist, title, number_of_tracks=''):
album = {'artist_name':artist, 'title':title}
if number_of_tracks!='':
album['number of tracks'] = number_of_tracks
return album
while True:
print("\n(enter 'q' at any time to quit)")
a_name = input("Artist name: ")
if a_name == 'q':
break
Title = input("Title: ")
if Title == 'q':
break
Album = make_album(a_name.title(), Title.title())
print(Album)
运行结果:
(enter 'q' at any time to quit)
Artist name: Taylor Swift
Title: Reputation
{'artist_name': 'Taylor Swift', 'title': 'Reputation'}
(enter 'q' at any time to quit)
Artist name: q
Q 8-9 魔术师 : 创建一个包含魔术师名字的列表, 并将其传递给一个名为show_magicians() 的函数, 这个函数打印列表中每个魔术师的名字。
Q 8-10 了不起的魔术师 : 在你为完成练习8-9而编写的程序中, 编写一个名为make_great() 的函数, 对魔术师列表进行修改, 在每个魔术师的名字中都加入字样“the Great”。 调用函数show_magicians() , 确认魔术师列表确实变了。
Q 8-11 不变的魔术师 : 修改你为完成练习8-10而编写的程序, 在调用函数make_great() 时, 向它传递魔术师列表的副本。 由于不想修改原始列表, 请返回修改后的列表, 并将其存储到另一个列表中。 分别使用这两个列表来调用show_magicians() , 确认一个列表包含的是原来的魔术师名字, 而另一个列表包含的是添加了字样“the Great”的魔术师名字。
知识点:传递列表
代码:
#8-9,8-10,8-11
def show_magicians(magicians):
for magician in magicians:
print(magician.title())
def make_great(magicians):
for index,magician in enumerate(magicians):
magicians[index] = 'the Great '+ magician
return magicians
Magicians = ['Liu Qian','Yif','unknown']
#Magicians = make_great(Magicians)
#show_magicians(Magicians)
great_magicians = make_great(Magicians[:])
show_magicians(Magicians)
show_magicians(great_magicians)
运行结果:
Liu Qian
Yif
Unknown
The Great Liu Qian
The Great Yif
The Great Unknown
Q 8-14 汽车 : 编写一个函数, 将一辆汽车的信息存储在一个字典中。 这个函数总是接受制造商和型号, 还接受任意数量的关键字实参。 这样调用这个函数: 提供必不可少的信息, 以及两个名称—值对, 如颜色和选装配件。 这个函数必须能够像下面这样进行调用:car = make_car('subaru', 'outback', color='blue', tow_package=True)。打印返回的字典, 确认正确地处理了所有的信息。
知识点:传多参
代码:
#8-14
def make_car(manufacturer,model,**info):
new_car = {}
new_car['manufacturer'] = manufacturer
new_car['model'] = model
for key,value in info.items():
new_car[key] = value
return new_car
car = make_car('subaru','outback',color = 'blue', tow_package = True)
print(car)
运行结果:
{'manufacturer': 'subaru', 'model': 'outback', 'color': 'blue', 'tow_package': True}