defdescrible_pet(animal_type, pet_name):"""显示宠物信息"""print("\n I have a "+ animal_type +".")print("My "+ animal_type +" 's name is "+ pet_name.title()+".")
describle_pet('hamster','harry')
describle_pet('dog','willie')
结果为
位置实参的顺序很重要
8.2.2 关键字实参
defdescrible_pet(animal_type, pet_name):"""显示宠物信息"""print("\n I have a "+ animal_type +".")print("My "+ animal_type +" 's name is "+ pet_name.title()+".")
describle_pet(animal_type='hamster',pet_name='harry')
describle_pet(animal_type='dog',pet_name='willie')
结果和上面的一样
8.2.3 默认值
给形参设置默认值,若该形参没有收到传递的实参值,则会使用该默认值
defdescrible_pet(pet_name,animal_type='dog'):"""显示宠物信息"""print("\n I have a "+ animal_type +".")print("My "+ animal_type +" 's name is "+ pet_name.title()+".")
describle_pet(pet_name='willie')
或
describle_pet('willie')
defbuild_person(first_name, last_name):"""返回一个字典,其中包含有关一个人的信息"""
person ={'first': first_name.title(),'last': last_name.title()}return person
musician = build_person('jimi','hendrix')print(musician)
结果为
若年龄为实参可选项
defbuild_person(first_name, last_name, age =''):"""返回一个字典,其中包含有关一个人的信息"""
person ={'first': first_name.title(),'last': last_name.title()}if age:
person['age']= age
return person
musician = build_person('jimi','hendrix',27)print(musician)
musician = build_person('jimi','hendrix')print(musician)
结果为
8.3.4 结合使用函数和 while 循环
defget_formatted_name(first_name,last_name, middle_name=''):"""返回整洁的姓名"""
full_name = first_name +' '+ middle_name +' '+ last_name
return full_name.title()whileTrue:print("\nPlease tell me your name:")print("(enter 'q' at any time to quit)")
f_name =input("First name: ")if f_name =='q':break
m_name =input("Middle name(if you not middle name and please into Enter to next): ")if m_name =='q':break
l_name =input("Last name: ")if l_name =='q':break
formatted_name = get_formatted_name(f_name,l_name,m_name)print("\nHello, "+ formatted_name +"!")
结果为
8.4 传递列表
defgreet_users(names):"""向列表中的每一位用户都发出简单的问候"""for name in names:
msg ="Hello, "+ name.title()+"!"print(msg)
以列表的方式来传递参数,此时列表是一个参数
usernames =['hannah','ty','margot']
greet_users(usernames)
结果为
8.4.1 在函数中修改列表
首先创建一个列表,其中包含一些要打印的设计
unprinted_designs =['iphone case','robot pendant','dodecahedron']
completed_models=[]
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
current_design = unprinted_designs.pop()
模拟根据设计制作3D打印模型的过程
print("Printing model: "+ current_design)
completed_models.append(current_design)
显示打印好的所有模型
print("\nThe following models have been printed:")for comleted_model in completed_models:print(comleted_model)
defmake_pizza(*toppings):"""打印顾客点的所有配料"""print("\nMaking a pizza wiith the following toppings ")for topping in toppings :print("\n- "+ topping)
make_pizza('perreroni')
make_pizza('mushrooms','green peppers','extra cheese')
结果为
8.5.1 结合使用位置实参和任意数量实参
defmake_pizza(size,*toppings):"""打印顾客点的所有配料"""print("\nMaking a "+str(size)+" -inch pizza wiith the following toppings ")for topping in toppings :print("- "+ topping)
make_pizza(16,'perreroni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
结果为
8.5.2 使用任意数量的关键字实参
**user_info 在形参中为 创建一个名为user_info的空字典,可以传递任意数量的实参
使用方法 location = ’ beijing ’ country = ‘China’
defbuild_profile(first, last,**user_info):"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile ={}
profile['first_name']= first
profile['last_name']= last
读取 **user_info 字典的内容,并返回给profile 字典
for key, value in user_info.items():
profile[key]= value
return profile
user_profile = build_profile('abert','einstein',
location='princeton'
field='physics')for key,value in user_profile.items():print("- "+ key +": "+ value)print(user_profile)
结果为
8.6 将函数存储在模块中
8.6.1 导入整个模块
模块文件需要放在引用该模块的文件同等的目录下
创建 pizza.py
defmake_pizza(size,*toppings):"""打印顾客点的所有配料"""print("\nMaking a "+str(size)+" -inch pizza wiith the following toppings ")for topping in toppings :print("- "+ topping)
给make_pizza函数取别名为 mp
from pizza import make_pizza as mp
mp(16,'perreroni')
mp(12,'mushrooms','green peppers','extra cheese')
给 pizza 模块取别名为 p
import pizza as p
p.make_pizza(16,'perreroni')
p.make_pizza(12,'mushrooms','green peppers','extra cheese')
8.6.5 导入模块中的所有函数
from pizza improt *
make_pizza(16,'perreroni')
make_pizza(12,'mushrooms','green peppers','extra cheese')