python编程 从入门到实践 第八章 函数 及课后题

来源:互联网 发布:应用特征数据库升级 编辑:程序博客网 时间:2024/06/14 02:36
#char 8 函数#定义函数#第一类:无参数,无返回值类型def greet_user():#greet functionprint('Hello')greet_user()#第二类:加入了一个参数:def greet_user(username):#another greet functionprint("Hello "+username.title()+" !")greet_user('jack')#实参与形参的区别:#形参:函数完成工作所需要的信息 #实参:传递给函数的信息#传递实参-位置实参,排序即与其输出有关def describe_pet(animal_type,pet_name):print('\n I have a '+animal_type+" .")print('my '+animal_type+"'s name is "+pet_name.title())describe_pet('dog','tom')#关键字实参,即在输入参数的时候加上参数名字describe_pet(animal_type='dog',pet_name='sarah')#此时即可调换顺序了describe_pet(pet_name='jackson',animal_type='pig')#关于默认值,默认值要放在后一个参数里def describe_pet(pet_name,animal_type='dog'):print('\n I have a '+animal_type+" .")print('my '+animal_type+"'s name is "+pet_name.title())describe_pet(pet_name='jack')describe_pet('jack')#若为该参数提供了实参,则函数会忽视默认值#8.3返回值def get_formatted_name(firstname,lastname):full_name=firstname+" "+lastnamereturn full_name.title()a=get_formatted_name('jackson','chan')print(a)#让实参变成可选#即让可选参数放在最后,用其等于空字符串即可,若有需要则加入该参数,若无需要就忽略def get_formatted_name(firstname,lastname,middlename=''):if middlename:full_name=firstname+" "+middlename+' '+lastnameelse:full_name=firstname+" "+lastnamereturn full_name.title()a=get_formatted_name('john','lee','hooker')b=get_formatted_name('jack','chan')print(a)print(b)#返回字典def build_preson(firstname,lastname):#接收参数封装到字典中person={'first':firstname,'last':lastname}return persona=build_preson('jimi','hendrix')print(a)def build_another_person(firstname,lastname,age=''):person={'first':firstname,'last':lastname}if age:person['age']=agereturn persona=build_another_person('jimi','hendrix',27)print(a)#函数和while结合循环def get_formatted_name(firstname,lastname):full_name=firstname+" "+lastnamereturn full_name.title()while True:print('\n please tell me your name')print("(enter 'q' at any time to quit)")f_name=input('firstname')if f_name =='q' :breakl_name=input('lastname')if l_name=='q':breakformatted_name=get_formatted_name(f_name,l_name)print('\n Hello, '+formatted_name+'!')#传递列表及在函数中修改列表def greet_users(names):for name in names:msg='Hello, '+ name.title()+" !"print(msg)username=['harry','ty','margot']unprinted_design=['iphone case','robot pendant','dodecahedron']completed_models=[]while unprinted_design:current_design=unprinted_design.pop()print('printing model: '+current_design)completed_models.append(current_design)print("\n The following models have been printed: ")for completed_model in completed_models:print(completed_model)#改变列表:def print_models(unprinted_design,completed_models):while unprinted_design:current_design=unprinted_design.pop()print('printing models'+ current_design)completed_models.append(current_design)def show_completed_models(completed_models):print('\n the following models have been printed:')for completed_model in completed_models:print(completed_model)print_models(unprinted_design,completed_models)show_completed_models(completed_models)#由于采用了pop,会导致原列表被修改,如果不希望修改元列表,可以使用其副本#既是list[:],这可以保证原列表不会遭到改变而函数结果与原来一致#8.5传递任意数量的实参def make_pizza(*toppings):print(toppings)make_pizza('mushroom','green been')def make_pizza(*toppings):print('\n making a pizza with the following toppings:')for topping in toppings:print('-'+topping)#结合位置参数def make_pizza(size,*toppings):print('\n making a '+str(size) +'inch pizza with the following toppings:')for topping in toppings:print('-'+topping)#使用任意数量的关键字实参#**user_info相当于传入了一个字典def build_profile(first,last,**user_info):profile={}profile['first_name']=firstprofile['last_name']=lastfor key,value in user_info.items():profile[key]=valuereturn profile#8-6将函数存储在模块中#即在一个模块中写函数,在另一个模块中调用该模块#eg:import pizza 还有 Import pizza as p#或者从特定的模块中导入特定的函数#from pizza import make_pizza #也可以用*导入某个模块的整个函数,即是from pizza import *

课后题

# char 8 homework#8-1def display_message():print("this session is learning function")display_message()#8-2def favourite_book(title):print('one of my favourite books is '+ title.title())favourite_book('harry potter')#8-3def make_shirt(size,logo):print('the shirt is '+size+" size and print"+logo)make_shirt('middle','python')make_shirt(size='middle',logo='python')#8-4def make_shirt(size='large',logo='i love python'):print('the shirt is '+size+" size and print "+logo)make_shirt() make_shirt(size='middle')make_shirt(logo='notebook')#8-5def describe_city(city_name,city_country='china'):print(city_name+" is belong to "+city_country)describe_city('shanghai')describe_city('hangzhou')describe_city('Reykjavik',city_country='Iceland')#8-6def city_country(city,country):full=city+" , "+countryreturn fulla=city_country('shanghai','china')print(a)#8-7def make_album(singer_name,album_name,songs_number=""):message={}message['singer_name']=singer_namemessage['album_name']=album_nameif songs_number:message['songs_number']=songs_numberreturn messagea=make_album('sudalv',' chunriguang ',20)print(a)#8-8while True:ablum_message={}print("\n please input the message of singer's name")print("(enter 'q' to quit)")singer_name=input("singer's name")if singer_name == 'q':breakalbum_name=input("ablum's name")if album_name=='q':breaksongs_number=input('songs_number')if songs_number=='q':breakelif songs_number=='':ablum_message=make_album(singer_name,album_name)else:number=songs_numberablum_message=make_album(singer_name,album_name,number)print(ablum_message)#8-9def show_magicians(magicians):for magician in magicians:print(magician.title())magicians=['jay chou','liu qian','yifu']show_magicians(magicians)#8-10def make_great(magicians):for index,magician in enumerate(magicians):magicians[index]='the great'+magicianreturn magiciansa=make_great(magicians)show_magicians(magicians)#8-11a=make_great(magicians[:])show_magicians(magicians)print(a)#8-12def making_sandwich(*toppings):print('your sandwich has following toppings')for topping in toppings:print(topping)making_sandwich('pork','egg')#8-13#8-14def make_car(name,factory,**car_info):car_mess={}car_mess['name']=namecar_mess['factory']=factoryfor key,value in car_info.items():car_mess[key]=valuereturn car_messa=make_car=('subaru','outback',color='blue',two_package=True)print(a)