第 8 章 函数 函数是带名字的代码块,用于完成具体的工作。要执行函数定义的任务,可调用该函数。
函数可反复调用;
使用函数将使程序的编写、阅读、测试和修改都更容易。
8.1 定义函数 1 2 3 4 5 def greet_user (): """显示简单的问候语""" print ("Hello!" ) greet_user()
函数定义:
用 def 定义函数名;
函数名后必须有一对括号;
最后冒号结束函数的定义。
文档字符串:
描述函数的用途;
用三个单引号或双引号括起;
写在函数体的首行;
用来生成函数的文档。
文档字符串(扩展):
函数调用:
8.1.1 向函数传递信息 在函数名后的括号内添加 username ,就可在函数内使用你给 username 的任何值。
1 2 3 4 5 def greet_user (username ): """显示简单的问候语""" print ("Hello, " + username.title() + "!" ) greet_user('jesse' )
8.1.2 实参和形参 形参:是函数定义中的参数变量。 实参:调用函数时传递给函数的信息。
很多人分不清楚实参、形参,见了勿惊。
8.2 传递实参 位置实参:要去实参与形参的顺序相同。 关键字实参:每个实参都由变量名和值组成。
8.2.1 位置实参 在函数调用时,按照形参的顺序,依次填入实参。
1 2 3 4 5 6 def describe_pet (animal_type, pet_name ): """显示宠物的信息""" print ("\nI have a " + animal_type + "." ) print ("My " + animal_type + "'s name is " + pet_name.title() + "." ) describe_pet('hamster' , 'harry' )
调用函数多次
位置实参的顺序很重要
8.2.2 关键字实参
直接在实参中将把名称和值关联起来。
无需考虑实参的顺序,因为已经清楚各值的用途。
务必准确指定函数定义中的形参名。
1 2 3 4 5 6 def describe_pet (animal_type, pet_name ): """显示宠物的信息""" print ("\nI have a " + animal_type + "." ) print ("My " + animal_type + "'s name is " + pet_name.title() + "." ) describe_pet(animal_type='hamster' , pet_name='harry' )
8.2.3 默认值 可给每个形参指定默认值。 函数调用时没有实参,则会使用这个形参的默认值。 形参定义默认值后,可在函数调用时省略相应的实参。
1 2 3 4 5 6 def describe_pet (pet_name, animal_type='dog' ): """显示宠物的信息""" print ("\nI have a " + animal_type + "." ) print ("My " + animal_type + "'s name is " + pet_name.title() + "." ) describe_pet(pet_name='willie' )
8.2.4 等效的函数调用 函数会有多种同等效果的调用方式,特别当有形参有默认值时:
1 2 3 4 5 6 7 8 9 10 11 12 13 def describe_pet (pet_name, animal_type='dog' ): """显示宠物的信息""" print ("\nI have a " + animal_type + "." ) print ("My " + animal_type + "'s name is " + pet_name.title() + "." ) describe_pet('willie' ) describe_pet(pet_name='willie' ) describe_pet('harry' , 'hamster' ) describe_pet(pet_name='harry' , animal_type='hamster' ) describe_pet(animal_type='hamster' , pet_name='harry' )
8.2.5 避免实参错误 下面代码有意的未给函数提供实参,导致产生了错误的提示。错误信息中指出了导致问题的位置,以及需要的实参个数与形参的名称。
1 2 3 4 5 6 7 8 9 10 11 12 def describe_pet (animal_type, pet_name ): """显示宠物的信息""" print ("\nI have a " + animal_type + "." ) print ("My " + animal_type + "'s name is " + pet_name.title() + "." ) describe_pet() Traceback (most recent call last): File "pets.py" , line 6 , in <module> describe_pet() TypeError: describe_pet() missing 2 required positional arguments: 'animal_type' and 'pet_name'
为形参提供良好的描述性名称,将能让错误信息更有帮助。
8.3 返回值 返回值 :函数返回的值称为返回值 。使用 return 将值返回到调用函数的代码行。
8.3.1 返回简单值 下面函数接受名和姓并返回整洁的姓名:
1 2 3 4 5 6 7 def get_formatted_name (first_name, last_name ): """返回整洁的姓名""" full_name = first_name + ' ' + last_name return full_name.title() musician = get_formatted_name('jimi' , 'hendrix' ) print (musician)
8.3.2 让实参变成可选的 可通过为实参设置默认值,从而让实参为可选:
1 2 3 4 5 6 7 8 9 10 11 12 13 def get_formatted_name (first_name, last_name, middle_name='' ): """返回整洁的姓名""" if middle_name: full_name = first_name + ' ' + middle_name + ' ' + last_name else : full_name = 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)
8.3.3 返回字典 函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。
1 2 3 4 5 6 7 8 9 def build_person (first_name, last_name, age='' ): """返回一个字典,其中包含有关一个人的信息""" person = {'first' : first_name, 'last' : last_name} if age: person['age' ] = age return person musician = build_person('jimi' , 'hendrix' , age=27 ) print (musician)
8.3.4 结合使用函数和 while 循环 把函数放到 while 循环中,程序将不断的问候,直到输入的名后姓是 ‘q’ 为止:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 def get_formatted_name (first_name, last_name ): """返回整洁的姓名""" full_name = first_name + ' ' + last_name return full_name.title() while True : print ("\nPlease tell me your name:" ) print ("(enter 'q' at any time to quit)" ) f_name = input ("First name: " ) if f_name == 'q' : break l_name = input ("Last name: " ) if l_name == 'q' : break formatted_name = get_formatted_name(f_name, l_name) print ("\nHello, " + formatted_name + "!" )
8.4 列表传递 定义两个函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def print_models (unprinted_designs, completed_models ): """ 模拟打印每个设计,直到没有未打印的设计为止 打印每个设计后,都将其移到列表completed_models中 """ while unprinted_designs: current_design = unprinted_designs.pop() print ("Printing model: " + current_design) completed_models.append(current_design) def show_completed_models (completed_models ): """显示打印好的所有模型""" print ("\nThe following models have been printed:" ) for completed_model in completed_models: print (completed_model)
调用上面的定义的函数:
1 2 3 4 5 unprinted_designs = ['iphone case' , 'robot pendant' , 'dodecahedron' ] completed_models = [] print_models(unprinted_designs, completed_models) show_completed_models(completed_models)
每个函数都应只负责一项具体的工作 。
8.4.2 禁止函数修改列表 使用切片传入列表的副本:
1 print_models(unprinted_designs[:], completed_models)
仅在必要的时候才创建副本,因为副本的创建会占用内存,在处理大列表时尤其如此。
8.5 传递任意数量的实参 当预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参。
形参名 *toppings 中的星号让 Python 创建一个名为 toppings 的空元组,并将收到的所有值都封装到这个元组中。
不管收到的是一个值还是三个值,这个函数都能妥善地处理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def make_pizza (*toppings ): """打印顾客点的所有配料""" print (toppings) """概述要制作的比萨""" print ("\nMaking a pizza with the following toppings:" ) for topping in toppings: print ("- " + topping) make_pizza('pepperoni' ) make_pizza('mushrooms' , 'green peppers' , 'extra cheese' ) Making a pizza with the following toppings: - pepperoni Making a pizza with the following toppings: - mushrooms - green peppers - extra cheese
8.5.1 结合使用位置实参和任意数量实参 如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。基于上述函数定义,Python将收到的第一个值存储在形参 size 中,并将其他的所有值都存储在元组 toppings 中。
1 2 3 4 5 6 7 8 9 def make_pizza (size, *toppings ): """概述要制作的比萨""" print ("\nMaking a " + str (size) + "-inch pizza with the following toppings:" ) for topping in toppings: print ("- " + topping) make_pizza(16 , 'pepperoni' ) make_pizza(12 , 'mushrooms' , 'green peppers' , 'extra cheese' )
8.5.2 使用任意数量的关键字实参 形参 **user_info 中的两个星号让 Python 创建一个名为 user_info 的空字典,并将收到的所有名称—值对都封装到这个字典中。在这个函数中,可以像访问其他字典那样访问 user_info 中的名称—值对。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def build_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' , field='physics' ) print (user_profile){'first_name' : 'albert' , 'last_name' : 'einstein' , 'location' : 'princeton' , 'field' : 'physics' }
8.6 将函数存储在模块中 将函数存储在被称为模块 的独立文件中,再将模块导入 到主程序中。import 语句允许在当前运行的程序文件中使用模块中的代码。
pizza.py
1 2 3 4 5 6 def make_pizza (size, *toppings ): """概述要制作的比萨""" print ("\nMaking a " + str (size) + "-inch pizza with the following toppings:" ) for topping in toppings: print ("- " + topping)
Python读取这个文件时,代码行import pizza让 Python 打开文件 pizza.py,并将其中的所有函数都复制到这个程序中。
1 2 3 4 import pizzapizza.make_pizza(16 , 'pepperoni' ) pizza.make_pizza(12 , 'mushrooms' , 'green peppers' , 'extra cheese' )
如果你使用这种import 语句导入了名为module_name.py 的整个模块,就可使用下面的语法来使用其中任何一个函数:
1 module_name.function_name()
8.6.2 导入特定的函数 导入模块中的在指定函数:
1 from module_name import function_name
通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数:
1 from module_name import function_0, function_1, function_2
若使用这种语法,调用函数时就无需使用句点。由于我们在 import 语句中显式地导入了函数function_0() ,因此调用它时只需指定其名称。
8.6.3 使用 as 给函数指定别名 为函数指别名的通用语法,如下:
1 from module_name import function_name as fn
示例:
1 2 3 from pizza import make_pizza as mpmp(16 , 'pepperoni' )
8.6.4 使用 as 给模块指定别名 给模块指定别名的通用语法,如下:
1 import module_name as mn
8.6.5 导入模块中的所有函数 使用星号(* )运算符可让Python导入模块中的所有函数:
1 2 3 4 from pizza import *make_pizza(16 , 'pepperoni' ) make_pizza(12 , 'mushrooms' , 'green peppers' , 'extra cheese' )
慎用这种方式。 会因为出现同名函数被覆盖的情况。
建议:
导入整个模块,使用句点表示法;
导入进需要的函数。
8.7 函数编写指南 命名:
给形参指定默认值时,等号两边不要有空格:
1 def function_name (parameter_0, parameter_1='default value' )
每个函数都应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字符串格式。
如果形参很多,导致函数定义的长度超过了79字符,可在函数定义中输入左括号后按回车键,并在下一行按两次Tab键,从而将形参列表和只缩进一层的函数体区分开来。
1 2 3 4 def function_name ( parameter_0, parameter_1, parameter_2, parameter_3, parameter_4, parameter_5 ): function body...
如果程序或模块包含多个函数,可使用两个空行将相邻的函数分开。 所有的 import 语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序。
8.8 小结 学的内容:
如何编写函数;
如何传递实参;
如何使用位置实参与关键字实参;
如何接受任意数量的实参;
如何编写显示输出和返回值的函数;
如何把函数与列表、字典、if、while 组合使用;
如何把函数储存到模块中;
如何调用模块中的函数;
编写函数的规范。
函数的优点:
可重用;
仅需修改一处;
让程序易于阅读;
易于调试和测试。
完整的学习笔记列表