####8-1 消息 :編寫一個名為display_message() 的函數,它打印一個句子,指出你在本章學的是什么。調用這個函數,確認顯示的消息正確無誤。
def display_message():
print("初識函數")
print("調用成功無誤")
display_message()
####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("《鬼谷子》")
####8-3 T恤 :編寫一個名為make_shirt() 的函數,它接受一個尺碼以及要印到T恤上的字樣。這個函數應打印一個句子,概要地說明T恤的尺碼和字樣。
- 使用位置實參調用這個函數來制作一件T恤;再使用關鍵字實參來調用這個函數。
def make_shirt(size, logo):
print("輸入尺碼為" + str(size) + "\n輸入打印的文字為" + str(logo) + "\n")
make_shirt("M","HAPPY")
make_shirt(size="L", logo="GLAD")
####8-4 大號T恤 :修改函數make_shirt() ,使其在默認情況下制作一件印有字樣“I love Python”的大號T恤。調用這個函數來制作如下T恤:一件印有默認字樣的大號T 恤、一件印有默認字樣的中號T恤和一件印有其他字樣的T恤(尺碼無關緊要)。
def make_shirt(size, logo="I love Python"):
print("輸入尺碼為" + str(size) + "\n輸入打印的文字為" + str(logo) + "\n")
make_shirt("L",)
make_shirt("M",)
make_shirt("S", "PYTHON")
####8-5 城市 :編寫一個名為describe_city() 的函數,它接受一座城市的名字以及該城市所屬的國家。這個函數應打印一個簡單的句子,如Reykjavik is in Iceland 。給用於存儲國家的形參指定默認值。為三座不同的城市調用這個函數,且其中至少有一座城市不屬於默認國家。
def describe_city(name, country = 'China'):
print(name.title() + " is in " + country.title())
describe_city('shanghai')
describe_city('beijing', country = 'china')
describe_city(name = 'paris', country = 'france')
####8-6 城市名 :編寫一個名為city_country() 的函數,它接受城市的名稱及其所屬的國家。這個函數應返回一個格式類似於下面這樣的字符串:"Santiago, Chile"
def city_country(city, country):
full = city + "." + country
return full.title()
complete = city_country('beijing', 'china')
print(complete)
complete = city_country('boston', 'us')
print(complete)
complete = city_country('paris', 'french')
print(complete)
####8-7 專輯 :編寫一個名為make_album() 的函數,它創建一個描述音樂專輯的字典。這個函數應接受歌手的名字和專輯名,並返回一個包含這兩項信息的字典。使用這個函數創建三個表示不同專輯的字典,並打印每個返回的值,以核實字典正確地存儲了專輯的信息。
- 給函數make_album() 添加一個可選形參,以便能夠存儲專輯包含的歌曲數。如果調用這個函數時指定了歌曲數,就將這個值添加到表示專輯的字典中。調用這個函數,並至少在一次調用中指定專輯包含的歌曲數。
def make_album(singer_name, album_name, song_number=" "):
if song_number:
x = {"singer_name":singer_name, "album_name":album_name,"song_number":song_number}
else:
x = {"singer_name":singer_name, "album_name":album_name}
return x
a = make_album("a", "b")
b = make_album("c", "d", "1")
c = make_album("e", "f", "11")
print(a)
print(b)
print(c)
####8-8 用戶的專輯 :在為完成練習8-7編寫的程序中,編寫一個while 循環,讓用戶輸入一個專輯的歌手和名稱。獲取這些信息后,使用它們來調用函 數make_album() ,並將創建的字典打印出來。在這個while 循環中,務必要提供退出途徑。
def make_album(singer_name, album_name, song_number=""):
if song_number:
x = {"singer_name":singer_name, "album_name":album_name,"song_number":song_number}
else:
x = {"singer_name":singer_name, "album_name":album_name}
return x
while True:
singer = input("輸入歌手名字(輸入'q'即可退出)")
if singer == 'q':
break
album = input("輸入專輯名字(輸入'q'即可退出)")
if album == 'q':
break
song = input("輸入歌曲數量(輸入'q'即可退出)")
if song == 'q':
break
conplete = make_album(singer, album, song)
print(conplete)
####8-9 魔術師 :創建一個包含魔術師名字的列表,並將其傳遞給一個名為show_magicians() 的函數,這個函數打印列表中每個魔術師的名字。
mn= ['magic_1','magic_2', 'magic_3']
def show_magicians(mn):
for i in mn:
print(i)
show_magicians(mn)
####8-10 了不起的魔術師 :在你為完成練習8-9而編寫的程序中,編寫一個名為make_great() 的函數,對魔術師列表進行修改,在每個魔術師的名字中都加入字樣“the Great”。調用函數show_magicians() ,確認魔術師列表確實變了。
mn = ['magic_1','magic_2', 'magic_3']
cn = []
def make_great(mn,cn):
while mn:
current = mn.pop()
current = "The Great" + current
cn.append(current)
def show_magicians(cn):
for i in cn:
print(i)
make_great(mn, cn)
show_magicians(cn)
####8-11 不變的魔術師 :修改你為完成練習8-10而編寫的程序,在調用函數make_great() 時,向它傳遞魔術師列表的副本。由於不想修改原始列表,請返回修改后的 列表,並將其存儲到另一個列表中。分別使用這兩個列表來調用show_magicians() ,確認一個列表包含的是原來的魔術師名字,而另一個列表包含的是添加了字 樣“the Great”的魔術師名字。
mn = ['magic_1','magic_2', 'magic_3']
cn = []
def make_great(mn,cn):
while mn:
current = mn.pop()
current = "The Great" + current
cn.append(current)
def show_magicians(cn):
for i in cn:
print(i)
make_great(mn[:],cn)
show_magicians(mn)
show_magicians(cn)
####8-12 三明治 :編寫一個函數,它接受顧客要在三明治中添加的一系列食材。這個函數只有一個形參(它收集函數調用中提供的所有食材),並打印一條消息,對顧客點的三明治進行概述。調用這個函數三次,每次都提供不同數量的實參。
def sandwich_make(*information):
print("添加食材: ")
for i in information:
print("——" + i)
sandwich_make('1','2','3')
sandwich_make('4','5','6')
sandwich_make('7','8','9')
####8-13 用戶簡介 :復制前面的程序user_profile.py,在其中調用build_profile() 來創建有關你的簡介;調用這個函數時,指定你的名和姓,以及三個描述你的鍵-值對。
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
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('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
information = build_profile("中", "國")
print(information)
china = build_profile("zhong","guo", nation="中國", city="北京")
print(china)
####8-14 汽車 :編寫一個函數,將一輛汽車的信息存儲在一個字典中。這個函數總是接受制造商和型號,還接受任意數量的關鍵字實參。這樣調用這個函數:提供必不可 少的信息,以及兩個名稱—值對,如顏色和選裝配件。這個函數必須能夠像下面這樣進行調用:
- car = make_car('subaru', 'outback', color='blue', tow_package=True)
- 打印返回的字典,確認正確地處理了所有的信息。
def make_car(manufacturer, model, **number):
"""Build a dictionary containing everything we know about a user."""
cars = {}
cars['制造商'] = manufacturer
cars['型號'] = model
for key, value in number.items():
cars[key] = value
return cars
car = make_car("法拉利", "高性能跑車", 顏色="赤焰紅", tow_package=True)
print(car)
####8-15 打印模型 :將示例print_models.py中的函數放在另一個名為printing_functions.py的文件中;在print_models.py的開頭編寫一條import 語句,並修改這個文件以使用導入的函數。
#printing_models.py 創建一個py文件
def print_models(unprinted_designs, completed_models):
"""
Simulate printing each design, until there are none left.
Move each design to completed_models after printing.
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
# Simulate creating a 3d print from the design.
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
#printing_functions.py 新建一個py文件
import printing_models
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
printing_models.print_models(unprinted_designs, completed_models)
printing_models.show_completed_models(completed_models)
####8-16 導入 :選擇一個你編寫的且只包含一個函數的程序,並將這個函數放在另一個文件中。在主程序文件中,使用下述各種方法導入這個函數,再調用它: import module_name import module_name as mn from module_name import * from module_name import function_name #未懂 from module_name import function_name as fn #未懂
####8-17 函數編寫指南 :選擇你在本章中編寫的三個程序,確保它們遵循了本節介紹的函數編寫指南。