初识函数------了解函数的定义、函数的参数、函数的返回值、说明文档的书写、函数的嵌套使用、变量的作用域(全局变量与局部变量)

文章目录


一、什么是函数?

函数是组织好的、可重复使用的代码段,用于实现单一或相关联功能的封装。如同生活中的工具,函数能让我们避免重复造轮子,提高开发效率和代码可维护性。

二、函数定义与调用

2.1 基本语法

python 复制代码
def 函数名(参数):
    """函数说明文档"""
    函数体
    return 返回值

2.2 示例演示

定义问候函数

python 复制代码
def greet(name):
    """显示简单的问候语"""
    print(f"Hello, {name}!")

调用函数

python 复制代码
greet("Alice")  # 输出:Hello, Alice!
greet("Bob")    # 输出:Hello, Bob!

三、函数参数详解

3.1 位置参数

python 复制代码
def calculate_area(length, width):
    return length * width

print(calculate_area(5, 3))  # 输出:15

3.2 默认参数

python 复制代码
def power(base, exponent=2):
    return base ** exponent

print(power(3))     # 输出:9
print(power(2, 4))  # 输出:16

3.3 可变参数

python 复制代码
def sum_all(*numbers):
    total = 0
    for n in numbers:
        total += n
    return total

print(sum_all(1, 2, 3))  # 输出:6

3.4 关键字参数

python 复制代码
def build_profile(**info):
    profile = {}
    for key, value in info.items():
        profile[key] = value
    return profile

user = build_profile(name="Alice", age=25, occupation="Engineer")
print(user)  # 输出:{'name': 'Alice', 'age': 25, 'occupation': 'Engineer'}

四、返回值与文档说明

4.1 返回多个值

python 复制代码
def calculate(a, b):
    return a+b, a-b, a*b

sum_result, sub_result, mul_result = calculate(8, 5)

4.2 编写文档字符串

python 复制代码
def quadratic(a, b, c):
    """
    解一元二次方程
    参数:
        a: 二次项系数
        b: 一次项系数
        c: 常数项
    返回:
        方程的实数解元组
    """
    discriminant = b**2 - 4*a*c
    x1 = (-b + discriminant**0.5) / (2*a)
    x2 = (-b - discriminant**0.5) / (2*a)
    return x1, x2

五、函数嵌套与作用域

5.1 嵌套函数示例

python 复制代码
def outer():
    print("外层函数被调用")
    
    def inner():
        print("内层函数被调用")
    
    inner()

outer()

输出:

外层函数被调用

内层函数被调用

5.2 变量作用域

python 复制代码
global_var = "全局变量"

def test_scope():
    local_var = "局部变量"
    print(global_var)  # 可以访问全局变量
    
test_scope()
print(local_var)  # 报错:NameError

5.3 global关键字

python 复制代码
count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 输出:1

六、综合案例

python 复制代码
def temperature_converter(value, unit):
    """
    温度单位转换器
    参数:
        value: 温度值
        unit: 原始单位('C'或'F')
    返回:
        转换后的温度值(保留两位小数)
    """
    if unit == 'C':
        converted = value * 9/5 + 32
        return round(converted, 2)
    elif unit == 'F':
        converted = (value - 32) * 5/9
        return round(converted, 2)
    else:
        raise ValueError("无效的温度单位")

print(temperature_converter(37, 'C'))  # 输出:98.6
print(temperature_converter(100, 'F')) # 输出:37.78
相关推荐
E_ICEBLUE1 小时前
Python 控制 PDF 页面大小、页边距、页面方向与缩放
python·pdf
Rubin智造社2 小时前
04月17日AI每日参考:Claude Opus 4.7正式发布,智元机器人大会今日开幕
大数据·人工智能·机器学习·claude code·智元机器人·deepseek v4·claude opus 4.7
Polar__Star3 小时前
如何结合计划任务实现自动定时备份任务配置_全自动化运维管理
jvm·数据库·python
weixin_580614008 小时前
如何提取SQL日期中的年份_使用YEAR或EXTRACT函数
jvm·数据库·python
2301_813599558 小时前
SQL生产环境规范_数据库使用最佳实践
jvm·数据库·python
李可以量化8 小时前
QMT 量化实战:用 Python 实现线性回归通道,精准识别趋势中的支撑与压力(下)
python·qmt·量化 qmt ptrade
a9511416428 小时前
Go 中通过 channel 传递切片时的数据竞争与深拷贝解决方案
jvm·数据库·python
Dxy12393102168 小时前
Python 使用正则表达式将多个空格替换为一个空格
开发语言·python·正则表达式
qq_189807038 小时前
如何修改RAC数据库名_NID工具在集群环境下的改名步骤
jvm·数据库·python
zhangchaoxies9 小时前
如何检测SQL注入风险_利用模糊测试技术发现漏洞
jvm·数据库·python