Chapter8笔记(函数)---课后题

#8-1 消息 :编写一个名为displaymessage() 的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误
def displaymessage():
    """我学到了一些东西"""
    print('I learnt how to create a function!')
displaymessage()
#结果
I learnt how to create a function!
#8-2 喜欢的图书 :编写一个名为favorite_book() 的函数,其中包含一个名为title 的形参。这个函数打印一条消息,
# 如One of my favorite books is Alice in Wonderland 。调用这个函数,并将一本图书的名称作为实参传递给它。
def favorite_book(title):
    print("One of my favorite books is "+title)
favorite_book('Alice in Wonderland')
#结果
One of my favorite books is Alice in Wonderland

使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。

#8-3 T恤 :编写一个名为make_shirt() 的函数,它接受一个尺码以及要印到T恤上的字样。这个函数应打印一个句子,
# 概要地说明T恤的尺码和字样。使用位置实参调用这个函数来制作一件T恤;再使用关键字实参来调用这个函数。
def make_shirt(size,words):
    print("the T-shirt's size and words are "+size+" and "+words)
make_shirt('M','run the world!')
make_shirt(words='run the world!',size='M')

#结果
the T-shirt's size and words are M and run the world!
the T-shirt's size and words are M and run the world!
#8-4 大号T恤 :修改函数make_shirt() ,使其在默认情况下制作一件印有字样“I love Python”的大号T恤。
# 调用这个函数来制作如下T恤:一件印有默认字样的大号T恤、一件印有默认字样的中号T恤和一件印有其他字样的T恤(尺码无关紧要)。
def make_shirt(size,words='I love Python'):
    print("the T-shirt's size and words are "+size+" and "+words)
make_shirt('L')
make_shirt('M')
make_shirt('S',words='I love running')
#结果
the T-shirt's size and words are L and I love Python
the T-shirt's size and words are M and I love Python
the T-shirt's size and words are S and I love running
#8-5 城市 :编写一个名为describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。
# 这个函数应打印一个简单的句子,如Reykjavik is inIceland 。给用于存储国家的形参指定默认值。
# 为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。
def describe_city(cityname,country='China'):
    print(cityname+" is belong with "+country)
describe_city('Shanghai')
describe_city('Beijing')
describe_city('Tokyo',country='Japan')
#结果
Shanghai is belong with China
Beijing is belong with China
Tokyo is belong with Japan
#8-6 城市名 :编写一个名为citycountry() 的函数,它接受城市的名称及其所属的国家。
# 这个函数应返回一个格式类似于下面这样的字符"Santiago, Chile",至少使用三个城市-国家对调用这个函数,并打印它返回的值。
def citycountry(cityname,country):
    print(cityname.title()+", "+country.title())
citycountry("shanghai","china")
citycountry("beijing","china")
citycountry("newyork","america")
#结果
Shangghai, China
Beijing, China
Newyork, America
#8-7 专辑 :编写一个名为make_album() 的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使
#用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。给函数make_album() 添加一个可选形参,以便能够存储专辑包含的歌曲数。
# 如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。
def make_album(singername,albumname):
    albums={'Singer': singername,'Album': albumname}
    print(albums)
make_album('Angela Cheung','Blue Eye')
make_album('Leslie Cheung','I')
make_album('QingFeng Wu','Sudalv')
#结果
{'Singer': 'Angela Cheung', 'Album': 'Blue Eye'}
{'Singer': 'Leslie Cheung', 'Album': 'I'}
{'Singer': 'QingFeng Wu', 'Album': 'Sudalv'}
#8-8 用户的专辑 :在为完成练习8-7编写的程序中,编写一个while 循环,让用户输入一个专辑的歌手和名称。获取这些信息后,
# 使用它们来调用函数make_album() ,并将创建的字典打印出来。在这个while 循环中,务必要提供退出途径。
while True:
    """输出歌手的名字和专辑名"""
    print("you could enter 'q' to quit this program")
    singername=input("Enter singername: ")
    if singername=='q':
        break
    albumname=input("Enter albumname: ")
    if albumname=='q':
        break
    a1=make_album(singername,albumname)
    print(a1)
#结果
you could enter 'q' to quit this program
Enter singername: Sudalv
Enter albumname: Summer Fever
{'Singer': 'Sudalv', 'Album': 'Summer Fever'}
you could enter 'q' to quit this program
Enter singername: Angela Zhang
Enter albumname: Visible Wings
{'Singer': 'Angela Zhang', 'Album': 'Visible Wings'}
you could enter 'q' to quit this program
Enter singername: q

切片表示法[:] 创建列表的副本

#8-9 魔术师 :创建一个包含魔术师名字的列表,并将其传递给一个名为show_magicians() 的函数,
#这个函数打印列表中每个魔术师的名字。
def show_magicians(magicians):
    for magician in magicians:
        print(magician)
magician3=['John','Jack','Jackson']
show_magicians(magician3)
#结果
John
Jack
Jackson

# 8-10 了不起的魔术师 :在你为完成练习8-9而编写的程序中,编写一个名为make_great() 的函数,对魔术师列表进行修改,
# 在每个魔术师的名字中都加入字样“the Great”。调用函数show_magicians() ,确认魔术师列表确实变了。
def make_great(magician3,showmag):
    for magic in magician3:
        magic="the Great "+magic
        showmag.append(magic)
def show_magicians(showmag):
    while showmag:
        print(showmag.pop())
showmag=[]
make_great(magician3,showmag)
show_magicians(showmag)
#结果
the Great Jackson
the Great Jack
the Great John
# 8-11 不变的魔术师 :修改你为完成练习8-10而编写的程序,在调用函数make_great() 时,向它传递魔术师列表的副本。
# 由于不想修改原始列表,请返回修改后的列表,并将其存储到另一个列表中。分别使用这两个列表来调用show_magicians()
# 确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“the Great”的魔术师名字。
def make_great(magician3,showmag):
    while magician3:
        magic="the Great "+magician3.pop()
        showmag.append(magic)
def show_magicians(magician3,showmag):
    for show in showmag:
        print(show)
    for magician in magician3:
        print(magician)
showmag=[]
magician3=['John','Jack','Jackson']
make_great(magician3[:],showmag)
show_magicians(magician3,showmag)
#结果
the Great Jackson
the Great Jack
the Great John
John
Jack
Jackson

任意数量实参:必须在函数定义中将接纳任意数量实参的形参放在最后  如 make_pizza(size, *toppings)

任意数量的关键字实参: 如  build_profile(first, last, **user_info)

#8-12 三明治 :编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),
# 并打印一条消息,对顾客点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。
def food(*sources):
    for source in sources:
        print(source)
food("fish","beef","meat")
print("------------------")
food("mutton","fish","beef","meat","chicken")
print("------------------")
food("beef")
#结果
fish
beef
meat
------------------
mutton
fish
beef
meat
chicken
------------------
beef
# 8-13 用户简介 :复制前面的程序user_profile.py,在其中调用build_profile() 来创建有关你的简介;
# 调用这个函数时,指定你的名和姓,以及三个描述你的键-值对。
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
user_profile = build_profile('Helen', 'Wang',
                             location='Fuzhou',
                             field='cs',
                             weather='rainy')
print(user_profile)
#结果
{'first_name': 'Helen', 'last_name': 'Wang', 'location': 'Fuzhou', 'field': 'cs', 'weather': 'rainy'}
#8-14 汽车 :编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。
# 这样调用这个函数:提供必不可少的信息,以及两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:
# car = make_car('subaru', 'outback', color='blue', tow_package=True)
def make_car(producer,size,**carinfos):
    cars={}
    cars['producer']=producer
    cars['size']=size
    for key,value in carinfos.items():
        cars[key]=value
    return cars
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
#结果
{'producer': 'subaru', 'size': 'outback', 'color': 'blue', 'tow_package': True}

给形参指定默认值时,等号两边不要有空格 

#8-15 打印模型 :将示例print_models.py中的函数放在另一个名为printing_functions.py的文件中;
# 在print_models.py的开头编写一条import 语句,并修改这个文件以使用导入的函数。
"""print_models.py"""
from printing_functions import make_car
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
"""print_models.py"""
def make_car(producer,size,**carinfos):
    cars={}
    cars['producer']=producer
    cars['size']=size
    for key,value in carinfos.items():
        cars[key]=value
    return cars
#结果
{'producer': 'subaru', 'size': 'outback', 'color': 'blue', 'tow_package': True}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值