610's Algorithm Teaching

函数与模块

函数基础

函数是一段可重用的代码块,用于执行特定任务。函数可以提高代码的可读性和可维护性。

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

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

result = add(5, 3)
print(f"5 + 3 = {result}")
greet("张三")

函数参数

Python函数支持多种参数传递方式,包括位置参数、关键字参数、默认参数等。

# 位置参数
def greet(name, age):
    print(f"{name}今年{age}岁")

greet("张三", 25)

# 关键字参数
greet(age=30, name="李四")

# 默认参数
def greet_with_default(name, age=20):
    print(f"{name}今年{age}岁")

greet_with_default("王五") # 使用默认年龄

可变参数

Python支持可变数量的参数,使用*args和**kwargs语法。

# 可变位置参数
def sum_all(*args):
    total = 0
    for num in args:
        total += num
    return total

print(sum_all(1, 2, 3, 4, 5)) # 输出:15

# 可变关键字参数
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

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

返回值

函数可以返回一个或多个值,使用return语句。

# 返回单个值
def calculate_area(radius):
    return 3.14 * radius ** 2

area = calculate_area(5)
print(f"面积是:{area}")

# 返回多个值
def get_min_max(numbers):
    return min(numbers), max(numbers)

minimum, maximum = get_min_max([1, 5, 3, 9, 2])
print(f"最小值:{minimum}, 最大值:{maximum}")

作用域

Python有局部作用域和全局作用域,变量在函数内部定义的是局部变量,在外部定义的是全局变量。

x = 10 # 全局变量

def test_scope():
    x = 20 # 局部变量
    print(f"函数内部x = {x}")

test_scope() # 输出:函数内部x = 20
print(f"函数外部x = {x}") # 输出:函数外部x = 10

# 使用global关键字
def modify_global():
    global x
    x = 30

modify_global()
print(f"修改后x = {x}") # 输出:修改后x = 30

匿名函数

Python支持lambda表达式创建匿名函数,适用于简单的函数。

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

# 与内置函数结合使用
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # 输出:[1, 4, 9, 16, 25]

模块基础

模块是包含Python定义和语句的文件,用于组织代码和实现代码重用。

# 导入模块
import math
print(math.pi) # 输出:3.14159...
print(math.sqrt(16)) # 输出:4.0

# 导入特定函数
from math import sqrt, pi
print(sqrt(25)) # 输出:5.0
print(pi) # 输出:3.14159...

# 使用别名
import numpy as np
import pandas as pd

常用内置模块

  • math:数学函数和常量
  • random:随机数生成
  • datetime:日期和时间处理
  • os:操作系统接口
  • sys:系统相关的参数和函数
  • json:JSON数据处理
  • re:正则表达式操作

创建自定义模块

可以创建自己的Python模块,然后在其他程序中导入使用。

# mymodule.py
def greet(name):
    return f"你好,{name}!"

def calculate_circle_area(radius):
    return 3.14 * radius ** 2

# main.py
import mymodule
print(mymodule.greet("张三"))
print(mymodule.calculate_circle_area(5))

学习建议

  • 理解函数的作用域和生命周期
  • 掌握不同参数传递方式的适用场景
  • 合理使用默认参数和可变参数
  • 学会使用模块组织代码
  • 了解常用内置模块的功能
  • 养成良好的函数命名和文档习惯
返回Python教程