教材第8章课后练习
8-1 消息
def display_message():
print('本章学的是函数')
display_message()
8-2 喜欢的图书
def favorite_book(title):
print('One of my favorite books is', title)
favorite_book('Alice in Wonderland')
8-3 T恤
def make_shirt(size, word):
print('T恤的尺码是:', size, '\nT恤的字样是:', word)
make_shirt(size='XXL', word='Life is short. I use Python.')
8-4 大号T恤
def make_shirt(size='L', word='I love Python'):
print('T恤的尺码是:', size, '\nT恤的字样是:', word)
make_shirt()
make_shirt(size='M')
make_shirt(word='I hate Python')
8-5 城市
def describe_city(name, country='China'):
print(name, 'is in', country)
describe_city('Tokyo', 'Japan')
describe_city('Beijing')
describe_city('Shenzhen')
8-6 城市名
def city_counrty(name, country):
return name+', '+country
print(city_counrty('Tokyo', 'Japan'))
print(city_counrty('NewYork', 'USA'))
print(city_counrty('Guangzhou', 'China'))
8-7 专辑
def make_album(singer_name, album_name, songs=0):
album = {}
album['singer name'] = singer_name
album['album name'] = album_name
if songs != 0:
album['songs'] = songs
return album
print(make_album('刘若英', '在一起', 5))
print(make_album('刘德华', '谢谢你的爱', 1))
print(make_album('刘若英', '我们没有在一起'))
8-8 用户的专辑
def make_album(singer_name, album_name, songs=0):
album = {}
album['singer name'] = singer_name
album['album name'] = album_name
if songs != 0:
album['songs'] = songs
return album
while True:
singer_name = input('请输入歌手的名字(输入q退出):')
if singer_name == 'q':
break
album_name = input('请输入专辑的名字(输入q退出):')
if album_name == 'q':
break
print(make_album(singer_name, album_name))
8-9 魔术师
def show_magicians(magicians):
for magician in magicians:
print(magician)
show_magicians(['克里斯·安吉尔', '大卫·科波菲尔', '胡迪尼'])
8-10 了不起的魔术师
def show_magicians(magicians):
for magician in magicians:
print(magician)
# ~ 不行的版本
# ~ def make_great(magicians):
# ~ magicians = ['the Great '+magician for magician in magicians]
# ~ def make_great(magicians):
# ~ magicians = list(map((lambda magician: 'the Great '+magician), magicians))
# ~ def make_great(magicians):
# ~ for magician in magicians:
# ~ magician = 'the Great '+magician
def make_great(magicians):
for i in range(len(magicians)):
magicians[i]='The Great '+magicians[i]
magicians = ['克里斯·安吉尔', '大卫·科波菲尔', '胡迪尼']
make_great(magicians)
show_magicians(magicians)
8-11 不变的魔术师
def show_magicians(magicians):
for magician in magicians:
print(magician)
# ~ 不行的版本
# ~ def make_great(magicians, new_magicians):
# ~ new_magicians = ['the Great '+magician for magician in magicians]
# ~ def make_great(magicians, new_magicians):
# ~ new_magicians = list(map((lambda magician: 'the Great '+magician), magicians))
# ~ 可行的版本
# ~ def make_great(magicians, new_magicians):
# ~ new_magicians.clear() # 这句话是可行的
# ~ for magician in magicians:
# ~ new_magicians.append('the Great '+magician)
def make_great(magicians, new_magicians):
# new_magicians = [] # 在函数里赋值会错
for i in range(len(magicians)):
new_magicians.append('The Great '+magicians[i])
magicians = ['克里斯·安吉尔', '大卫·科波菲尔', '胡迪尼']
new_magicians= []
make_great(magicians[:], new_magicians)
show_magicians(magicians)
show_magicians(new_magicians)
8-12 三明治
def offer_sandwich(*ingredients):
print('Your sandwich includes:')
if not ingredients:
print('\tNothing')
for ingredient in ingredients:
print('\t', ingredient, sep='')
offer_sandwich('egg')
offer_sandwich('egg', 'ham', 'bacon')
offer_sandwich()
下面是对各种参数位置的一些研究。
def add(*bs, a): # 允许没有默认值的参数放在后面
res = a
for b in bs:
res += b
print(res)
add(1,2,a=5) # 必须加上a=,否则会出错
运行结果:
8
def add(*bs, a=1): # print函数的原型类似这样
res = a
for b in bs:
res += b
print(res)
add(1, 2, 3)
运行结果:
7
def add(**bs, a): # 这样是错的,traceback提示是SyntaxError,a如果想放在后面必须加默认值
res = a
for b in bs.values():
res += b
print(res)
def add(a, **bs):
res = a
for b in bs.values():
res += b
print(res)
add(1, b=2, c=3)
运行结果:
6
def add(*bs, **cs):
res = 0
for b in bs:
res += b
for c in cs.values():
res += c
print(res)
add(1, 2, 3) # 全部传给bs
add(1,2,3,c=4) # 1,2,3传给bs,c=4传给cs
运行结果:
6
10
def add(**bs, *cs): # 语法错误,说明任意数量的关键字参数必须放在最后
res = 0
for b in bs:
res += b
for c in cs.values():
res += c
print(res)
def add(*bs, a=0, **cs):
res = a
for b in bs:
res += b
for c in cs.values():
res += c
print(res)
add(1,2)
add(1,2,a=3)
add(1,2,a=3,b=4)
add(1,2,b=3)
运行结果:
3
6
10
6
结论:任意数量的参数和普通参数(有无默认值均可)可以互换位置,会导致函数对待参数的行为有一些区别,但是任意数量的关键字参数必须放在最后。
8-13 用户简介
def build_profile(first, last, **user_info):
'''创建一个字典,其中包含我们知道的有关用户的一切'''
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
my_profile = build_profile('Zicong', 'Huang',
location='Guangzhou',
field='computer',
grade=2016)
print(my_profile)
8-14 汽车
def make_car(manufacturer, model, **informations):
car = {}
car['manufacturer'] = manufacturer
car['model'] = model
for key, value in informations.items():
car[key] = value
return car
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
8-15 打印模型
print_models.py
import printing_functions
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
printing_functions.print_models(unprinted_designs, completed_models)
printing_functions.show_completed_models(completed_models)
printing_functions.py
def print_models(unprinted_designs, completed_models):
'''
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表completed_models中
'''
while unprinted_designs:
current_design = unprinted_designs.pop()
# 模拟根据设计制作3D打印模型的过程
print('Printing model: ' + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
'''显示打印好的所有模型'''
print('\nThe following models have been printed:')
for completed_model in completed_models:
print(completed_model)
8-16 导入
display_message.py
def display_message():
print('本章学的是函数')
main.py
# import display_message
# display_message.display_message()
# from display_message import display_message
# display_message()
# from display_message import display_message as dm
# dm()
# import display_message as dm
# dm.display_message()
from display_message import *
display_message()