Python编程:从入门到实践(第3版)

> 📖 **一起读书吧!** 加入《Python编程:从入门到实践》共读营 👉 [点击参加](https://mp.weixin.qq.com/s/ehe2vMrfAFscRLqbM9TF-g)

本讲内容

  • 定义和调用函数
  • 参数:位置参数、关键字参数、默认值
  • 返回值:单个值、多个值(返回元组)
  • 传递列表和字典
  • *args 和 **kwargs
  • lambda表达式
  • 函数风格指南

学习目标

把重复代码打包成可复用的工具 🧰


1. 定义函数

1
2
3
4
5
6
def greet_user(username):
"""显示简单的问候语"""
print(f"Hello, {username}!")

greet_user('jesse') # Hello, jesse!
greet_user('sarah') # Hello, sarah!

"""三引号""" 是 docstring,用于描述函数功能,help(函数名) 时会显示。

官方文档:4.8. Defining Functions

2. 位置参数和关键字参数

1
2
3
4
5
6
7
8
9
10
# 位置参数:按顺序传递
def describe_pet(animal_type, pet_name):
print(f"\n我有一只{animal_type}。")
print(f"它的名字是{pet_name}。")

describe_pet('仓鼠', '哈利') # 顺序很重要!
describe_pet('狗', '旺财')

# 关键字参数:顺序无关
describe_pet(pet_name='来福', animal_type='猫')

3. 默认参数

1
2
3
4
5
6
def describe_pet(pet_name, animal_type='dog'):
print(f"\n我有一只{animal_type}。")
print(f"它的名字是{pet_name}。")

describe_pet('旺财') # 使用默认值
describe_pet('花花', '兔子') # 覆盖默认值

⚠️ 默认参数必须放在非默认参数后面:def func(a, b=1)

官方文档:4.9.1. Default Argument Values

4. 返回值

1
2
3
4
5
6
7
8
9
10
11
12
def get_formatted_name(first_name, last_name):
full_name = f"{first_name} {last_name}"
return full_name.title()

name = get_formatted_name('eric', 'matthes')
print(name) # Eric Matthes

# 返回None(没有return语句时)
def greet(name):
print(f"Hello, {name}")
result = greet('jesse')
print(result) # None

返回字典

1
2
3
4
5
6
7
8
def build_person(first_name, last_name, age=None):
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person

musician = build_person('jimi', 'hendrix', age=27)
print(musician) # {'first': 'jimi', 'last': 'hendrix', 'age': 27}

5. 传递列表

1
2
3
4
5
6
def greet_users(names):
for name in names:
print(f"Hello, {name.title()}!")

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

在函数中修改列表

1
2
3
4
5
6
7
8
9
def print_models(unprinted, completed):
while unprinted:
current = unprinted.pop()
print(f"打印中: {current}")
completed.append(current)

unprinted = ['手机壳', '齿轮', '杯子']
completed = []
print_models(unprinted, completed)

如果不想修改原列表,传切片副本:print_models(unprinted[:], completed)

6. *args — 任意数量位置参数

1
2
3
4
5
6
7
8
def make_pizza(*toppings):
print("\n制作披萨,配料如下:")
for topping in toppings:
print(f" - {topping}")

make_pizza('蘑菇') # 单个
make_pizza('蘑菇', '青椒', '双层芝士') # 多个
# toppings 被收集成元组

官方文档:4.9.4. Arbitrary Argument Lists

7. **kwargs — 任意数量关键字参数

1
2
3
4
5
6
7
8
9
10
11
12
13
def build_profile(**user_info):
profile = {}
for key, value in user_info.items():
profile[key] = value
return profile

user = build_profile(
name='eric',
location='princeton',
field='physics'
)
print(user)
# {'name': 'eric', 'location': 'princeton', 'field': 'physics'}

8. lambda 表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
# 普通函数
def square(x):
return x ** 2

# lambda(一行匿名函数)
square = lambda x: x ** 2

# 实用场景:排序
players = [{'name': 'charles', 'age': 30},
{'name': 'li', 'age': 20},
{'name': 'alice', 'age': 25}]
players.sort(key=lambda p: p['age'])
print([p['name'] for p in players]) # ['li', 'alice', 'charles']

官方文档:4.9.6. Lambda Expressions

9. 函数风格指南

1
2
3
4
5
# ✅ 函数名用小写下划线:describe_pet()
# ✅ 类名用驼峰:Dog, Car, ElectricCar
# ✅ 模块名简短小写:random, json, csv
# ✅ docstring描述函数做什么
# ✅ 函数行数控制在屏幕高度内,太长就拆分

📚 官方文档参考


🎓 AI 编程实战课程

程序员晚枫专注AI编程培训,通过 《30讲 · AI编程训练营》,让小白也能用AI做出实际项目。