本章知识小结:
1、位置参数、关键字参数、默认值(传入参数是list[:]禁止函数修改列表)
2、list传递任意数量实参[]、* list传递多参多信息{ : }
3、匿名函数lambda x:(x%2==1)、filter、map
4、导入模块 import、from import、as
1、函数定义 形参(argument),类似下函数传入的names变量
实参(parameter),调用函数时传入的参数[‘hannah’, ‘ty’, ‘margot’]是实际存在的参数
1 2 3 4 5 6 7 8 def greet_users (names ): for name in names: msg = f"Hello, {name.title()} !" print (msg) usernames = ['hannah' , 'ty' , 'margot' ] greet_users(usernames)
2、传递实参 位置实参:按照顺序传入参数
关键字实参:定义的时候直接给默认值
1 2 3 4 5 def describe_pet (pet_name, animal_type='dog' ): print (f"\nI have a {animal_type} ." ) print (f"My {animal_type} 's name is {pet_name.title()} ." ) describe_pet(pet_name='willie' )
传入可选实参
1 2 3 4 5 6 7 8 9 10 11 12 def get_formatted_name (first_name, last_name, middle_name='' ): if middle_name: full_name = f"{first_name} {middle_name} {last_name} " else : full_name = f"{first_name} {last_name} " return full_name.title() musician = get_formatted_name('jimi' , 'hendrix' ) print (musician)musician = get_formatted_name('john' , 'hooker' , 'lee' ) print (musician)
3、返回值 函数内return值
4、传递任意数量的参数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 def make_pizza (size, *toppings ): print (f"\nMaking a {size} -inch pizza with the following toppings:" ) for topping in toppings: print (f"- {topping} " ) make_pizza(12 ,'aaa' ) make_pizza(12 ,'aaa' ,'bbb' ,'ccc' ) def build_profile (first, last, **user_info ): user_info['first_name' ] = first user_info['last_name' ] = last return user_info user_profile = build_profile('albert' , 'einstein' , location='princeton' , field='physics' ) print (user_profile)
5、匿名函数lambda 1 2 3 4 5 6 7 8 9 10 mylist = [1 ,2 ,3 ,4 ,5 ,6 ,7 ] lambda x:(x%2 ==1 )print (list (filter (lambda x:(x%2 ==1 ),mylist)))print (list (map (lambda x:(x%2 ==1 ),mylist)))
6、函数存储在模块中 导入整个模块 import xxx from xxx import *
导入模块的特定函数 from xxx import xxx
制定别名 from xxx import xxx as xx