跳到主要内容

函数基础与进阶

用函数组织代码,实现代码复用

函数概述

什么是函数

函数 是一段可重用的代码块,完成特定任务。

# 没有函数:重复代码
print("=" * 20)
print("欢迎光临")
print("=" * 20)

# 有了函数:封装复用
def welcome():
print("=" * 20)
print("欢迎光临")
print("=" * 20)

welcome() # 调用函数

函数的作用

  1. 代码复用:写一次,多处使用
  2. 模块化:把复杂问题分解
  3. 可读性:代码结构清晰
  4. 可维护性:修改一处,处处生效

定义与调用

基本语法

# 定义函数
def 函数名(参数列表):
"""文档字符串"""
函数体
return 返回值

# 调用函数
结果 = 函数名(参数)

简单函数

# 无参数无返回值
def say_hello():
print("Hello, World!")

say_hello() # 调用

# 有参数
def greet(name):
print(f"Hello, {name}!")

greet("张三") # Hello, 张三!

# 有返回值
def add(a, b):
return a + b

result = add(3, 5) # result = 8

文档字符串

def calculate_area(radius):
"""
计算圆的面积

参数:
radius: 圆的半径

返回:
圆的面积
"""
import math
return math.pi * radius ** 2

# 查看文档
print(calculate_area.__doc__)
help(calculate_area)

函数参数

位置参数

def power(base, exponent):
return base ** exponent

# 按位置传参
print(power(2, 3)) # 8
print(power(3, 2)) # 9

关键字参数

def greet(name, message):
print(f"{message}, {name}!")

# 按关键字传参(顺序可变)
greet(name="张三", message="你好")
greet(message="Hello", name="李四")

默认参数

def greet(name, message="你好"):
print(f"{message}, {name}!")

greet("张三") # 你好, 张三!
greet("李四", "Hello") # Hello, 李四!

# 注意:默认参数必须放在后面
# def func(a=1, b): # 错误
def func(a, b=1): # 正确
pass

可变参数 *args

# 接收任意数量的位置参数
def sum_all(*args):
print(type(args)) # <class 'tuple'>
return sum(args)

print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15

关键字可变参数 **kwargs

# 接收任意数量的关键字参数
def print_info(**kwargs):
print(type(kwargs)) # <class 'dict'>
for key, value in kwargs.items():
print(f"{key}: {value}")

print_info(name="张三", age=25, city="北京")

参数组合

# 参数顺序:普通参数、默认参数、*args、**kwargs
def example(a, b=10, *args, **kwargs):
print(f"a={a}, b={b}")
print(f"args={args}")
print(f"kwargs={kwargs}")

example(1, 2, 3, 4, x=5, y=6)
# a=1, b=2
# args=(3, 4)
# kwargs={'x': 5, 'y': 6}

返回值

返回单个值

def square(x):
return x ** 2

result = square(5) # 25

返回多个值

def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder # 返回元组

q, r = divide(10, 3)
print(f"商:{q}, 余数:{r}") # 商:3, 余数:1

无返回值

def print_hello():
print("Hello")
# 没有return语句,默认返回None

result = print_hello()
print(result) # None

提前返回

def check_age(age):
if age < 0:
return "年龄无效"
if age < 18:
return "未成年"
return "成年"

作用域

局部变量和全局变量

# 全局变量
global_var = "我是全局变量"

def example():
# 局部变量
local_var = "我是局部变量"
print(global_var) # 可以访问全局变量
print(local_var)

example()
print(global_var) # 可以
# print(local_var) # 错误:局部变量在外部不可见

global关键字

count = 0

def increment():
global count # 声明使用全局变量
count += 1

increment()
increment()
print(count) # 2

nonlocal关键字

def outer():
x = 10

def inner():
nonlocal x # 声明使用外层变量
x += 1
print(x)

inner() # 11
print(x) # 11

outer()

高级特性

匿名函数 lambda

# lambda 参数: 表达式
square = lambda x: x ** 2
print(square(5)) # 25

add = lambda a, b: a + b
print(add(3, 5)) # 8

# 常用于排序
students = [("张三", 85), ("李四", 92), ("王五", 78)]
students.sort(key=lambda x: x[1], reverse=True)
print(students) # [('李四', 92), ('张三', 85), ('王五', 78)]

函数作为参数

def apply(func, value):
return func(value)

def double(x):
return x * 2

result = apply(double, 5) # 10

# 使用内置函数
numbers = [1, -2, 3, -4, 5]
positives = list(filter(lambda x: x > 0, numbers))
print(positives) # [1, 3, 5]

squares = list(map(lambda x: x**2, numbers))
print(squares) # [1, 4, 9, 16, 25]

闭包

def make_counter():
count = 0

def counter():
nonlocal count
count += 1
return count

return counter

counter = make_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3

装饰器入门

def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"调用函数:{func.__name__}")
result = func(*args, **kwargs)
print(f"函数返回:{result}")
return result
return wrapper

@log_decorator
def add(a, b):
return a + b

add(3, 5)
# 调用函数:add
# 函数返回:8

递归函数

什么是递归

递归 = 函数调用自己

# 计算阶乘
def factorial(n):
if n <= 1: # 基准条件(终止条件)
return 1
return n * factorial(n - 1) # 递归调用

print(factorial(5)) # 120
# 5! = 5 * 4! = 5 * 4 * 3! = ...

斐波那契数列

def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)

for i in range(10):
print(fibonacci(i), end=" ")
# 0 1 1 2 3 5 8 13 21 34

递归注意事项

# 1. 必须有终止条件
# 2. 递归深度有限制(默认1000)
# 3. 可能效率较低

import sys
print(sys.getrecursionlimit()) # 默认1000

# 修改递归深度限制
sys.setrecursionlimit(2000)

实战示例

示例1:温度转换

def celsius_to_fahrenheit(celsius):
"""摄氏度转华氏度"""
return celsius * 9/5 + 32

def fahrenheit_to_celsius(fahrenheit):
"""华氏度转摄氏度"""
return (fahrenheit - 32) * 5/9

print(celsius_to_fahrenheit(100)) # 212.0
print(fahrenheit_to_celsius(212)) # 100.0

示例2:密码验证

def validate_password(password):
"""
验证密码强度
规则:至少8位,包含大小写字母和数字
"""
if len(password) < 8:
return False, "密码至少8位"

has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)

if not has_upper:
return False, "需要大写字母"
if not has_lower:
return False, "需要小写字母"
if not has_digit:
return False, "需要数字"

return True, "密码有效"

valid, message = validate_password("Abc12345")
print(message)

练习

练习1:计算列表统计

# 编写函数,返回列表的最大值、最小值、平均值

def stats(numbers):
# 参考答案
return max(numbers), min(numbers), sum(numbers)/len(numbers)

result = stats([1, 2, 3, 4, 5])
print(result) # (5, 1, 3.0)

练习2:判断回文

# 判断字符串是否是回文
def is_palindrome(s):
# 参考答案
s = s.lower().replace(" ", "")
return s == s[::-1]

print(is_palindrome("level")) # True
print(is_palindrome("hello")) # False

本章小结

  1. 函数定义:def 函数名(参数): 函数体 return 返回值
  2. 参数类型:位置参数、默认参数、*args、**kwargs
  3. 作用域:局部变量、全局变量、global、nonlocal
  4. 高级特性:lambda、闭包、装饰器
  5. 递归:函数调用自己,必须有终止条件

下一步

学会了函数,下一章学习列表与元组。

→ 继续阅读:19-列表与元组