python核心语法(四)- 函数

Python 核心语法(四)—— 函数
(初始Python篇 进阶版,2026 年最新,基于 Python 3.12/3.13)

这是 Python 中最重要、最灵活、最容易被面试深挖的核心语法之一。
掌握本篇后,你就能写出优雅、可复用、高性能的 Python 代码。


1. 函数基础语法(必须手敲 3 遍)

def 函数名(参数列表):
    """函数文档字符串(docstring)—— 强烈推荐写"""
    # 函数体
    return 返回值   # 可省略,返回 None

最简单例子

def greet(name):
    """向某人问好"""
    print(f"你好,{name}!")
    return f"问候完成:{name}"

# 调用
result = greet("张三")
print(result)

2. 函数参数的 5 种传递方式(重中之重!面试必考)

(1)位置参数(最常见)

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

print(power(2, 3))   # 8

(2)默认参数(面试高频!)

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

greet("李四")           # 你好,李四!
greet("王五", "早上好")  # 早上好,王五!

重要规则默认参数必须放在普通参数后面,且默认值只在定义时计算一次(坑!)

(3)关键字参数(key=value)

def student(name, age, city="北京"):
    print(name, age, city)

student(age=18, name="张三")   # 顺序可以乱写

(4)可变位置参数 *args(最灵活)

def add(*numbers):
    return sum(numbers)

print(add(1, 2, 3, 4, 5))   # 15
print(add(10, 20))          # 30

(5)可变关键字参数 **kwargs

def person_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

person_info(name="张三", age=18, city="上海", hobby="编程")

混合使用顺序规则(必须记住!):

def func(a, b, *args, c=10, **kwargs):
    pass
# 顺序:普通参数 → *args → 默认参数 → **kwargs

3. 返回值与多返回值(Python 特色)

def calculate(a, b):
    return a+b, a-b, a*b, a/b   # 自动打包成 tuple

sum_, diff, mul, div = calculate(10, 3)
print(sum_, diff, mul, div)

4. 作用域(LEGB 规则)—— 面试必问!

Python 查找变量顺序:L → E → G → B

x = 100          # Global

def outer():
    x = 50       # Enclosing(闭包作用域)

    def inner():
        x = 10   # Local
        print(x) # 10

    inner()
    print(x)     # 50

outer()
print(x)         # 100

global 与 nonlocal(修改外部变量):

x = 0
def counter():
    global x          # 声明使用全局变量
    x += 1
    return x

def outer():
    count = 0
    def inner():
        nonlocal count   # 修改外层函数的变量
        count += 1
        return count
    return inner

5. 高级函数特性(Pythonic 精华)

(1)lambda 匿名函数(一行函数)

add = lambda x, y: x + y
print(add(3, 5))   # 8

# 常用场景:排序、过滤、map
students = [('张三', 85), ('李四', 92), ('王五', 78)]
students.sort(key=lambda x: x[1], reverse=True)

(2)map、filter、reduce(函数式编程)

nums = [1, 2, 3, 4, 5]

# map:对每个元素应用函数
squares = list(map(lambda x: x**2, nums))          # [1,4,9,16,25]

# filter:筛选
evens = list(filter(lambda x: x % 2 == 0, nums))   # [2,4]

# reduce(需从 functools 导入)
from functools import reduce
total = reduce(lambda x, y: x + y, nums)           # 15

(3)递归函数(经典!)

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n-1)

print(factorial(5))   # 120

6. 装饰器(Decorator)—— Python 最优雅的特性之一

import time

def timer(func):
    """计时装饰器"""
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} 执行耗时: {end-start:.4f} 秒")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1.5)
    print("函数执行完成")

slow_function()

7. 一句话总结(面试 30 秒版)

“Python 函数支持位置参数、默认参数、args、*kwargs 四种参数类型,返回值可多个(自动打包 tuple)。变量查找遵循 LEGB 规则,可用 global/nonlocal 修改作用域。lambda、map/filter/reduce、装饰器、递归是 Python 函数式编程的精髓。”


本篇结束,你已经系统掌握了 Python 函数的所有核心知识!

下一讲预告(初始Python篇 第五讲):

  • 模块(module)与包(package)
  • __name__ == '__main__' 的真正含义
  • 常用标准库(os、sys、datetime、random、json 等)
  • 包管理与虚拟环境

想现在就看下一讲吗?

直接回复以下任意关键词,我立刻发出:

  • 下一讲 → 模块与包详解
  • 练习题 → 30 道函数专属练习 + 面试真题(带答案)
  • 装饰器 → 深入装饰器原理 + 多层装饰器 + 类装饰器
  • 项目 → 用函数写一个完整学生管理系统

继续加油!你现在离写出专业级 Python 代码只差最后几步了!🚀

文章已创建 5041

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部