网站首页 > 基础教程 正文
在 Python 中,函数是组织代码的重要工具(essential building blocks)
可以将重复的代码逻辑封装(encapsulate)成一个独立的单元
从而实现代码复用(reusable code)、模块化(enabled modularity)和更好的可读性(improved readability)。
下面我们将详细介绍如何定义和使用函数,包括参数、返回值、作用域、文档字符串以及高级用法。
1. 定义函数 (Defining Functions)
使用 def 关键字可以定义一个函数。函数名后面紧跟参数列表(parameter list),后面是冒号和缩进的代码块,这些代码构成了函数体(a colon, and an indented block of code that forms the function body)。
示例:
def greet():
"""
打招呼函数
(Function to greet)
"""
print("Hello, World!") # 输出问候语 (Print greeting)
greet() # 调用函数 (Call the function)
2. 参数与返回值 (Parameters and Return Values)
函数可以接收参数,并通过 return 返回结果。参数可以是必选参数、默认参数、可变参数或关键字参数。
(Functions can accept parameters and return a value using the return statement. Parameters can be required, default, variable-length, or keyword arguments.)
示例:传递参数并返回值
def add(a, b):
"""
返回两个数的和
(Return the sum of two numbers)
"""
return a + b
result = add(10, 5)
print("和是:" + str(result)) # 输出:15
示例:使用默认参数
def greet_user(name="Guest"):
"""
用于问候用户,默认用户名为 'Guest'
(Greet user; default name is 'Guest')
"""
print("Hello, " + name + "!")
greet_user("Alice") # 输出:Hello, Alice!
greet_user() # 输出:Hello, Guest!
3. 文档字符串 (Docstrings)
在函数内部使用三引号字符串(triple-quoted strings),可以为函数添加说明文档。这有助于代码的可读性和维护性,同时也能被 IDE 和帮助系统调用(be accessed by IDEs and help utilities)。
示例:
def multiply(a, b):
"""
计算两个数的乘积
(Calculate the product of two numbers)
参数:
a (int/float): 第一个数字 (first number)
b (int/float): 第二个数字 (second number)
返回:
int/float: 两个数字的乘积 (the product of the two numbers)
"""
return a * b
help(multiply) # 查看函数说明 (View function documentation)
4. 作用域与局部变量 (Scope and Local Variables)
函数内部定义的变量称为局部变量,仅在该函数内有效。全局变量(global variables)定义在函数外部,可在整个模块中访问(accessible throughout the module)。
示例:
global_var = "我是全局变量" # 全局变量 (Global variable)
def demo():
local_var = "我是局部变量" # 局部变量 (Local variable)
print(global_var) # 可以访问全局变量 (Can access global variable)
print(local_var)
demo()
# print(local_var) # 会报错,因为 local_var 在函数外不可访问 (Error: local_var not accessible)
5. Lambda 函数 (Lambda Functions)
Lambda 函数是匿名函数(anonymous functions)的一种简洁写法,适用于编写简单、短小的函数。
示例:
# 求两个数之和的匿名函数
sum_func = lambda x, y: x + y
print("Lambda 求和:" + str(sum_func(3, 4))) # 输出:7
6. 函数嵌套与闭包 (Nested Functions and Closures)
在一个函数内部可以定义另一个函数,这称为嵌套函数。如果内部函数(inner function)引用了(refers to)外部函数的变量,并在外部函数返回后仍能访问这些变量,这就是闭包(closure)。
示例:
def outer(msg):
message = msg # 外部变量
def inner():
print("内部消息:" + message)
return inner # 返回内部函数
my_func = outer("Hello from closure!")
my_func() # 调用闭包,输出内部消息
7. 高阶函数与内置函数 (Higher-Order Functions and Built-ins)
函数在 Python 中是第一类对象,允许将函数作为参数传递或作为返回值。常见的高阶函数有 map()、filter() 和 reduce()。
(Functions are first-class objects in Python. They can be passed as arguments or returned from other functions. Common higher-order functions include map(), filter(), and reduce().)
示例:使用 map 和 filter
numbers = [1, 2, 3, 4, 5]
# 使用 map 计算平方
squares = list(map(lambda x: x**2, numbers))
print("平方列表:" + str(squares)) # 输出:[1, 4, 9, 16, 25]
# 使用 filter 筛选偶数
evens = list(filter(lambda x: x % 2 == 0, numbers))
print("偶数列表:" + str(evens)) # 输出:[2, 4]
8. 小贴士与注意事项 (Tips & Caveats)
- 函数命名:选择有意义的函数名称,使用小写字母和下划线分隔(例如:calculate_sum)。
(Choose meaningful function names using lowercase letters and underscores.) - 保持函数单一职责:每个函数应只完成一项任务,避免函数逻辑过于复杂。
(Keep functions focused on a single task to improve readability and maintainability.) - 合理使用默认参数:默认参数可提高函数灵活性,但注意避免使用可变对象作为默认参数。
(Be cautious with default parameters, especially mutable types.) - 注重文档字符串:编写详细的 docstrings 方便自己和他人理解函数用途和用法。
(Write comprehensive docstrings for clarity.) - 测试函数:编写测试用例,确保函数在不同输入下都能正常运行。
(Test functions with various inputs to ensure reliability.)
★ 总结
掌握这些知识,你将能够编写出高效、模块化、易维护的代码。
(Understanding these concepts will empower you to write efficient, modular, and maintainable code.)
如果你觉得这篇教程对你有帮助,请点赞、收藏并关注我,一起进步吧! Happy coding!
猜你喜欢
- 2025-03-18 如何在 Python 中进行平方:完整指南
- 2025-03-18 怎样让 Python 代码更简洁高效?这些实用技巧别错过!
- 2025-03-18 Python 一行代码帮你节省数小时工作
- 2025-03-18 实战指南:Python 代码优化的常见技巧与思路大集合
- 2025-03-18 如何使用 Python 在 Excel 中创建、更新和删除表格
- 2025-03-18 Python 最大N个数与最小N个数的和
- 2025-03-18 Python高效办公:用自动化脚本批量处理Excel
- 2025-03-18 python基础函数(Python基础函数导入)
- 2025-03-18 别再死记硬背!Python函数知识点和练习题都在这里,速来挑战!
- 2025-03-18 Python函数:定义函数、参数传递、返回值、lambda 表达式
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)