函数

定义函数

1
2
3
4
5
def greet_user(): 
"""显示简单的问候语"""
print("Hello!")

greet_user()
Hello!
1
2
3
4
5
def greet_user(username): 
"""显示简单的问候语"""
print("Hello, " + username.title() + "!")

greet_user("gun")
Hello, Gun!

形参和实参

传递实参

  1. 位置实参(基于实参的顺序将函数调用中的每个实参都关联到函数定义中的一个形参)
  2. 关键字实参(是传递给函数的名称—值对)
  3. 默认值(编写函数时,可给每个形参指定默认值)

文档字符串
它的首行简述函数功能,第二行空行,第三行为函数的具体描述
你可以使用 __doc__(注意都是双下划线)调用函数中的文档字符串属性(如下)

1
2
3
4
5
6
7
8
9
10
# 位置实参
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('williea', 'dog')
describe_pet('dog', 'willie')
print(describe_pet.__doc__)
I have a hamster.
My hamster's name is Harry.

I have a williea.
My williea's name is Dog.

I have a dog.
My dog's name is Willie.
显示宠物的信息
1
2
3
4
5
6
7
# 关键字实参,实参顺序可任意
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(pet_name='harry', animal_type='hamster')
I have a hamster.
My hamster's name is Harry.
1
2
3
4
5
6
# 默认值
def describe_pet(animal_type, pet_name='willie'):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('dog')
I have a dog.
My dog's name is Willie.

注意:
Python依然将这个实参视为位置实参,因此如果函数调用中只包含宠物的名字,这个实参将关联到函数
定义中的第一个形参
简单来说,使用默认值时视为位置实参,有默认值的形参全部需放在后面
另外:由于显式地给animal_type提供了实参,因此Python会将忽略这个形参的默认值

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()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[32], line 6
      4     print("\nI have a " + animal_type + ".") 
      5     print("My " + animal_type + "'s name is " + pet_name.title() + ".") 
----> 6 describe_pet() 


TypeError: describe_pet() missing 2 required positional arguments: 'animal_type' and 'pet_name'

返回值


返回简单值

1
2
3
4
5
6
7
8
def get_formatted_name(first_name, last_name): 
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
print("Hello")
return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)
Hello
Jimi Hendrix

让实参变成可选的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 让实参变成可选的,就是在中间if、else判断
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)
Jimi Hendrix
John Lee Hooker

返回字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 返回字典
def build_person(first_name, last_name, age='',job=''):
"""返回一个字典,其中包含有关一个人的信息"""
first_name=first_name.title()
last_name=last_name.title()
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age

if job:
person['job'] = job
return person

musician = build_person('jimi', 'hendrix',22, 'doctor')
print(musician)
{'first': 'Jimi', 'last': 'Hendrix', 'age': 22, 'job': 'doctor'}

结合使用函数和 while 循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def get_formatted_name(first_name, last_name): 
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
return full_name.title()

# 这是一个无限循环! 使用“no”进行break终止
while True:
print("\nPlease tell me your name:")
f_name = input("First name: ")
l_name = input("Last name: ")

formatted_name = get_formatted_name(f_name, l_name)
print("\nHello, " + formatted_name + "!")

answer = input("Would you like to continue?")
if answer == "no":
break
Please tell me your name:

First name:  芊
Last name:  芊 龍

Hello, 芊 芊 龍!

Would you like to continue? no

传递列表

1
2
3
4
5
6
7
8
9
# 和传递值一样的
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!
  1. 在函数中修改列表
  2. 禁止函数修改列表

每个函数都应只负责一项具体的工作

要将列表的副本传递给函数
function_name(list_name[:])
比如print_models(unprinted_designs[:], completed_models)
切片表示法[:]创建列表的副本

传递任意数量的实参

1
2
3
4
5
6
def make_pizza(*toppings): 
"""打印顾客点的所有配料"""
print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中

1
2
3
4
5
6
7
8
def make_pizza(*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

使用任意数量的关键字实参

  1. 结合使用位置实参和任意数量实参
    • Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中
  2. 使用任意数量的关键字实参
    • 形参**user_info中的两个星号让Python创建一个名为user_info的空字典
    • 两个键—值对
      (location='princeton’和field=‘physics’),
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')
Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
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')
Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 使用任意数量的关键字实参
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'}

编写函数时,你可以以各种方式混合使用位置实参、关键字实参和任意数量的实参

模块

  • 函数的优点之一是,使用它们可将代码块与主程序分离
  • 模块是扩展名为 .py的文件,包含要导入到程序中的代码
  1. import module_name导入整个模块或py文件 module_name.function_name()
  2. from module_name import function_name from module_name import function_0, function_1, function_2 导入特定的函数 function_name()
  3. from module_name import function_name as fn使用as给函数指定别名 fn()
  4. import module_name as mn使用 as 给模块指定别名 mn.function_name()
  5. import module_name import *导入模块中的所有函数 function_name()

函数编写指南

给形参指定默认值时,等号两边不要有空格:
def function_name(parameter_0, parameter_1=‘default value’)
对于函数调用中的关键字实参,也应遵循这种约定:
function_name(value_0, parameter_1=‘value’)
形参过多可以使用缩减对齐
所有的import语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序
应给函数指定描述性名称,且只在其中使用小写字母和下划线。描述性名称可帮助你和别人明白代码想要做什么。给模块命名时也应遵循上述约定