题目参照《python编程——从入门到实践》第八章习题
8-1
def display_message(message):
print(message)
display_message('function')
8-2
def favorite_book(book):
print('One of my favorite books is '+book)
favorite_book('Alice in Wonderland')
8-5
def describe_city(city,country='Iceland'):
print(city+' is in '+country)
describe_city('Reykjavik')
describe_city('Hongkong','China')
describe_city(country='China',city='Guangzhou')
8-7、8-8
def make_album(singer,name,total_music=''):
album={'singer':singer,'name':name}
if total_music!='':
total_music=int(total_music)
album['total_music']=total_music
return album
while True:
singer=input("Please input the singer name:\n(enter 'e' at any time to exit)\n")
if singer=='e':
break
name=input("Please input the album name:\n(enter 'e' at any time to exit)\n")
if name=='e':
break
message='Please input how many music the album have:\n';
message+="(enter 'e' at any time to exit,enter 'd' when you don't know the number)\n"
total_music=input(message)
if total_music=='e':
break
if total_music=='d':
album=make_album(singer,name)
else:
album=make_album(singer,name,total_music)
print(album,end='\n\n')
8-9、8-10、8-11、8-16
magicans.py
from module import*
magicians=['Alice','Bob','Linko']
show_magicians(magicians)
new_magicians=make_great(magicians[:])
show_magicians(new_magicians)
show_magicians(magicians)
module.py
def show_magicians(magicians):
for magician in magicians:
print(magician)
def make_great(magicians):
for i in range(0,len(magicians)):
magicians[i]+=' the Great'
return magicians
8-14
def make_car(model,manufacturer,**car_info):
car={'manufacturer':manufacturer,'model':model}
for key,value in car_info.items():
car[key]=value
return car
car=make_car(model='outback',color='blue',two_package=True,manufacturer='subaru')
print(car)
勘误:
《python编程——从入门到实践》这本书中提到普通的形参必须放在形如*topping这种形参之前,但这种说法是完全错误的。
对于形如*topping的形参,可以写出如下可执行函数
def make_pizze(name,*toppings,size):
print('\nMaking a '+str(size)+'-inch pizza named '+name+' with the following toppings:')
for topping in toppings:
print('- '+topping)
make_pizze('aaa','mushrooms','green peppers','extra cheese',size=12)
证明python对于*topping形式的形参,在函数定义中并无过多限制。
而经过实验,在调用时,*topping前的实参必须按照位置实参形式传入,而*topping后的实参必须按照关键字实参形式传入。
而对于**car_info形式的形参,在函数定义中,必须位于其他形参之后,否则会报错。
同时经过实验,在调用时,可以使用关键字实参,把**car_info前形参的实参写在函数的任意位置。
虽然这些发现对于编写规范的python程序毫无意义,但暂且指出,防止大家见到诸如此类程序时发出“这为什么能执行”的惊叹声。