1 定义函数
def greet_user():
"""显示简单的问候语"""
print("Hello!")
greet_user()
- 第一行的代码行使用关键字def来告诉Python你要定义一个函数,这是函数定义。
- 第二行的文本是被称为文档字符串
(docstring)的注释,描述了函数是做什么的。 - 代码行print(“Hello!”)是函数体内的唯一一行代码, greet_user()只做一项工作:
打印Hello! - 要调用函数,可依次指定函数名以及用括号括起的必要信息,如第四行所示。
1.1 向函数传递信息
def greet_user(username):
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('jesse')
通过在这里添加username,
就可让函数接受你给username指定的任何值。
2 传递实参
2.1 位置实参
你调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参。
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')
调用describe_pet()时,需要按顺序提供一种动物类型和一个名字。例如,在前面的函数调用中,实参’hamster’存储在形参animal_type中,而实参’harry’存储在形参pet_name中。
注意:位置实参的顺序很重要,请确认函数调用中实参的顺序与函数定义中形参的顺序一致。
2.2 关键字实参
关键字实参是传递给函数的名称—值对。你直接在实参中将名称和值关联起来了,因此向函数传递实参时不会混淆。关键字实参让你无需考虑函数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途。
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')
2.3 默认值
编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时, Python将使用
指定的实参值;否则,将使用形参的默认值。
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')
这里修改了函数describe_pet()的定义,在其中给形参animal_type指定了默认值’dog’。这
样,调用这个函数时,如果没有给animal_type指定值, Python将把这个形参设置为’dog’:
I have a dog.
My dog's name is Willie
注意:Python依然将这个实参视为位置实参,因此如果函数调用中只包含宠物的名字,这个实参将关联到函数定义中的第一个形参。这就是需要将pet_name放在形参列表开头的原因所在。
3 返回值
在函数中,可使用return语句将值返回到调用函数的代码行。
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)
结果:
Jimi Hendrix
函数可返回任何类型的值,包括==列表==和==字典==等较复杂的数据结构。
4 传递列表
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
结果:
Hello, Hannah!
Hello, Ty!
Hello, Margot!
4.1 在函数中修改列表
将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的,这让你能够高效地处理大量的数据。
4.2 禁止函数修改列表
为解决这个问题,可向函数传
递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件。
要将列表的副本传递给函数,可以像下面这样做:
function_name(list_name[:])
5 传递任意数量的实参
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个==元组==中。
5.1 结合使用位置实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最
后。
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')
结果:
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
5.2 使用任意数量的关键字实参
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)
形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所
有名称—值对都封装到这个字典中。在这个函数中,可以像访问其他字典那样访问user_info中的名称—值对。
结果:
{'first_name': 'albert', 'last_name': 'einstein',
'location': 'princeton', 'field': 'physics'}
6 将函数存储在模块中
6.1 导入整个模块
要让函数是可导入的,得先创建模块。模块是扩展名为.py的文件,包含要导入到程序中的代码。
pizza.py
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
making_pizzas.py
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
6.2 导入特定的函数
making_pizzas2.py
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
若使用这种语法,调用函数时就无需使用句点。由于我们在import语句中显式地导入了函数
make_pizza(),因此调用它时只需指定其名称。
6.3 使用 as 给函数指定别名
making_pizzas3.py
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
6.4 使用 as 给模块指定别名
making_pizzas4.py
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
6.5 导入模块中的所有函数(不建议)
使用星号(*)运算符可让Python导入模块中的所有函数:
making_pizzas5.py
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
如果模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果:Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。
7 函数编写指南
- 每个函数都应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字符串格式;
- 给形参指定默认值时,等号两边不要有空格;
- 如果程序或模块包含多个函数,可使用两个空行将相邻的函数分开;
- 所有的import语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序.