python函数详解:提升代码效率和可读性的利器
函数是Python中组织代码、减少冗余的强大工具。它们是可复用的代码块,能够执行特定任务。Python函数分为两种:无返回值函数(void函数)和有返回值函数。
基本函数结构:
<code class="python">def function_name(arguments):
"""函数文档字符串"""
# 函数体</code>示例:无返回值函数
<code class="python">def greet():
"""打印问候语"""
print("Hello, world!")
greet() # 调用函数</code>输出:
立即学习“Python免费学习笔记(深入)”;
<code>Hello, world!</code>
示例:有返回值函数
<code class="python">def add(x, y):
"""返回两个数字的和"""
return x + y
sum = add(5, 3)
print(sum) # 输出 8</code>重要提示: 有返回值的函数,务必使用其返回值。
参数与关键字参数:
Python函数可以灵活地接受多个参数,主要有两种方式:
*args来接收任意数量的位置参数。key=value的形式传递,顺序无关紧要。可以使用**kwargs来接收任意数量的关键字参数。示例:位置参数
<code class="python">def calculate_sum(*numbers):
"""计算任意数量数字的和"""
total = 0
for number in numbers:
total += number
return total
print(calculate_sum(1, 2)) # 输出 3
print(calculate_sum(1, 2, 3, 4)) # 输出 10</code>示例:关键字参数
<code class="python">def display_details(name, **info):
"""打印个人信息"""
print(f"Name: {name}")
for key, value in info.items():
print(f"{key}: {value}")
display_details("Alice", age=30, city="New York", profession="Engineer")</code>示例:混合使用位置参数和关键字参数
<code class="python">def process_data(*items, action="sum"):
"""根据action参数执行不同的操作"""
if action == "sum":
return sum(items)
elif action == "average":
return sum(items) / len(items) if items else 0
else:
return "Invalid action"
print(process_data(1,2,3)) # 输出 6
print(process_data(1,2,3, action='average')) # 输出 2.0</code>位置参数和关键字参数必须放在函数参数列表的最后。
递归函数:
递归函数是指在函数内部调用自身。递归函数需要:
示例:阶乘计算
<code class="python">def factorial(n):
"""计算n的阶乘"""
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # 输出 120</code>
Lambda 函数 (匿名函数):
Lambda 函数是一种简短的匿名函数,通常用于简单的操作。
示例:
<code class="python">square = lambda x: x * x print(square(5)) # 输出 25</code>
map() 和 filter() 函数:
map() 函数对序列中的每个元素应用一个函数。filter() 函数根据条件筛选序列中的元素。示例:map()
<code class="python">numbers = [1, 2, 3, 4, 5] doubled_numbers = list(map(lambda x: x * 2, numbers)) print(doubled_numbers) # 输出 [2, 4, 6, 8, 10]</code>
示例:filter()
<code class="python">numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # 输出 [2, 4, 6]</code>
示例:消除重复代码
假设有两个函数都需要进行用户验证:
<code class="python">def register(username, password):
if validate_user(username, password):
print("Registration successful")
else:
print("Invalid credentials")
def login(username, password):
if validate_user(username, password):
print("Login successful")
else:
print("Invalid credentials")
def validate_user(username, password):
# 验证逻辑
return username != "" and password != ""</code>通过将验证逻辑封装到 validate_user 函数中,避免了代码重复。
最佳实践:
希望本文能帮助您更好地理解和运用Python函数,编写出更优雅、更高效的代码。
以上就是Python 教程 - 函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号