defdescribe_pet(animal_type, pet_name):"""显示宠物信息"""print("I have a "+ animal_type +".")print("My "+ animal_type +"'s name is "+ pet_name.title()+".")#位置实参:函数调用中实参的顺序与函数定义中形参的顺序一致
describe_pet('cat','penny')
describe_pet('dog','williw')##关键字实参:显示指出形参-实参对应的内容
describe_pet(animal_type='cat', pet_name='happy')
describe_pet(pet_name='blue', animal_type='dog')
形参默认值
#形参animal_type的默认值为dogdefdescribe_pet(pet_name, animal_type ='dog'):print("\nI have a "+ animal_type +".")print("My "+ animal_type +"'s name is "+ pet_name.title()+".")
describe_pet('yoki')
describe_pet('mmmi','cat')
#提取任意数量实参中元组的元素defprint_pizza(*toppings):'''概述要制作的披萨'''print("\nMaking a pizza with the following toppings: ")for topping in toppings:print("- "+ topping)
print_pizza('pepperoni')
print_pizza('mushrooms','green peppers','extra cheese')
传递任意数量的关键字实参
#**user_info表示任意数量的实参是 键值对 形式defbuild_profile(first, last,**user_info):'''创建一个字典,字典中包含用户的信息'''
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',
filed ='physics')print(user_profile)
6、将函数存储在模块中
导入整个模块(调用函数需要用 模块名.函数名 的形式)
#moudle_pizza.pydefmake_pizza(size,*toppings):print("\nMaking a pizza with the following toppings: ")for topping in toppings:print("- "+ topping)#moudle_make.py#导入整个模块,可以使用该模块中的所有函数import module_pizza
module_pizza.make_pizza(18,'pepperoni')
module_pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')
导入模块中的特定函数
#moudle_pizza.pydefmake_pizza(size,*toppings):print("\nMaking a pizza with the following toppings: ")for topping in toppings:print("- "+ topping)#moudle_make2.py#从模块module_pizza中导入函数make_pizzafrom module_pizza import make_pizza
make_pizza(18,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
用 as 给从模块中导入的函数指定别名
from module_pizza import make_pizza as mp
mp(18,'pepperoni')
mp(12,'mushrooms','green peppers','extra cheese')
用 as 给模块指定别名
import module_pizza as pizza
pizza.make_pizza(16,'mushrooms')
导入模块中的所有函数(可直接使用函数名)-不推荐
from module_pizza import*
make_pizza(18,'mushrooms')