Python 函数
定义函数使用 def, 参数, 返回值, and 默认实参.
你将学到
- 如何 定义函数使用 def
- 参数, 实参, and 返回值
- 默认实参 and keyword 实参
- 变量-长度实参使用 *args and **kwargs
- Docstrings and 为什么 应该编写它们
概念讲解
Defining a Function
Use the def keyword to define a function, followed by the name, parameters in parentheses, and a colon. The body is indented:
def greet(name):
return f"Hello, {name}!"
print(greet("Ada")) # Hello, Ada!
Parameters and Return Values
Functions accept parameters (inputs) and can return a value. If you do not include a 返回 statement, the function returns 无:
def add(a, b):
return a + b
result = add(3, 4) # 7
Default Arguments
You can give parameters default values, making them optional:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Ada") # Hello, Ada!
greet("Ada", "Hi") # Hi, Ada!
greet("Ada", greeting="Hey") # keyword argument
Warning: never use a mutable object (like a list) as a default argument. Default values are evaluated once when the function is defined, so the same list is shared across all calls:
# BAD — the list is shared across calls!
def add_item(item, items=[]):
items.append(item)
return items
# GOOD — create a new list each call
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
Keyword Arguments
You can pass arguments by name, which makes calls more readable and lets you skip optional parameters:
def create_user(name, age, role="用户", active=True):
return {"name": name, "age": age, "role": role, "active": active}
create_user("Ada", 25, role="admin", active=False)
*args and **kwargs
- **
*args** collects extra positional arguments into a tuple kwargs** collects extra keyword arguments into a dict
def sum_all(*args):
return sum(args)
sum_all(1, 2, 3, 4) # 10
def log(**kwargs):
for key, value in kwargs.items():
print(f"{键} = {值}")
log(user="Ada", action="登录", time="10:30")
Docstrings
A docstring is a triple-quoted string at the start of a function that documents what it does. It is accessible via help() and is essential for readable code:
def calculate_bmi(weight, height):
"""Calculate Body Mass Index.
Args:
weight: weight in kilograms
height: height in meters
Returns:
The BMI value (weight / height^2)
"""
return weight / (height ** 2)
Good docstrings explain the why, not just the what. Tools like Sphinx and IDEs use them to provide inline help.
示例代码
# Basic function with a return value
def greet(name, greeting="Hello"):
"""Return a greeting message."""
return f"{greeting}, {name}!"
print(greet("Ada"))
print(greet("Ada", greeting="Hi"))
# A function with multiple returns
def grade(score):
"""Convert a numeric score to a letter grade."""
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "F"
print(f"Score 85 earns: {grade(85)}")
# *args for variable positional arguments
def sum_all(*args):
"""Sum any number of arguments."""
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 15
# **kwargs for variable keyword arguments
def make_profile(**kwargs):
"""Build a user profile from keyword arguments."""
return kwargs
profile = make_profile(name="Ada", age=25, role="admin")
print(profile)
# Safe default argument pattern (avoid mutable defaults!)
def add_item(item, items=None):
"""Add an item to a list, creating a new list if none provided."""
if items is None:
items = []
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['b'] — not ['a', 'b']!
Shows 函数使用 defaults, multi-返回 grade 函数, *args, **kwargs, and safe 模式 for 可变默认实参. docstrings show 如何 document 函数.
动手试一试
- Math Evaluator
Evaluate 表达式 — 相似到 什么函数 computes and 返回.
- Regex Tester
函数经常 wrap regex logic — 测试模式 live.
常见错误
错误写法
Using 可变默认实参如 def f(项=[])
正确做法
默认实参是 evaluated 一次 at 定义时间, 所以相同列表是 shared 跨越所有 calls. Use def f(项=无): 项 = 项 or [] 到创建 fresh 列表每个 call.
错误写法
Forgetting 到返回值 and 获取无
正确做法
函数不使用 explicit 返回语句返回无. 如果你的函数应该 produce 值, 制作确定到 编写返回值. 这个是 常见源 的 NoneType 错误.
相关资源
相关代码片段
- 排序 Dictionary 通过值
函数那个排序 dictionary — practical 示例.
相关速查表
- Python Cheatsheet
函数定义, 实参, and docstring 引用.
练习 Python 函数
12 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。