【Python Homework】Chapter08 函数

8-1 消息 :编写一个名为display_message() 的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。
def favorite_book(book_name):
	print("One of my favorite books is " + book_name)

favorite_book("Alice in Wonderworld")


8-4 大号T恤 :修改函数make_shirt() ,使其在默认情况下制作一件印有字样“I love Python”的大号T恤。调用这个函数来制作如下T恤:一件印有默认字样的大号T恤、一件印有默认字样的中号T恤和一件印有其他字样的T恤(尺码无关紧要)。
def make_shirt(size = "L", words = "I love Python"):
	print("The size of the T-shirt is: " + size)
	print("The words in it are: " + words)
	
make_shirt()
make_shirt("M")	
make_shirt("M", "This is my shirt!")


8-5 城市 :编写一个名为describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子,如Reykjavik is in Iceland 。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。
def describe_city(city = 'Munich', country = 'Germany'):
	print(city + " is in " + country)
	
describe_city()
describe_city('Berlin')
describe_city('Guangzhou', 'China')


8-6 城市名 :编写一个名为city_country() 的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面这样的字符串:"Santiago, Chile"
def city_country(city, country):
	return city + ", " + country

print(city_country('Santiago', 'Chile'))
print(city_country('Munich', 'Germany'))
print(city_country('Guangzhou', 'China'))


8-7 专辑 :编写一个名为make_album() 的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使 用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。
给函数make_album() 添加一个可选形参,以便能够存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个 函数,并至少在一次调用中指定专辑包含的歌曲数。
def make_album(singer, album):
	return {'singer': singer, 'album': album}

print(make_album('Ed Sheeran', 'X'))
print(make_album('One direction', 'Take me home'))
print(make_album('Coldplay', 'Ghost stories'))

def make_album(singer, album, num = 0):
	return {'singer': singer, 'album': album, 'songs':num}

print(make_album('Coldplay', 'Ghost stories', 12))


8-10 了不起的魔术师 :在你为完成练习8-9而编写的程序中,编写一个名为make_great() 的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the Great”。调用函数show_magicians() ,确认魔术师列表确实变了。

def show_magicians(names):
	for name in names:
		print(name)
		
magics = ['Lalala', 'Hehehe', 'Eieiei']
magicb = []
show_magicians(magics)

def make_great(names,nameb):
	for name in names:
		nameb.append('The great ' + name)

make_great(magics, magicb)
show_magicians(magicb)


8-12 三明治 :编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。
def make_sandwich(*toppings):
	print("\nMaking a sandwich with the following toppings:")
	for topping in toppings:
		print("- " + topping)
		
make_sandwich('pepperoni')
make_sandwich('tomato', 'pineapple')
make_sandwich('mushrooms', 'green peppers', 'extra cheese')



2018.04.01 [08]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值