当前位置: 首页 > article >正文

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

文章目录

  • 一、什么是函数?
  • 二、函数定义与调用
    • 2.1 基本语法
    • 2.2 示例演示
  • 三、函数参数详解
    • 3.1 位置参数
    • 3.2 默认参数
    • 3.3 可变参数
    • 3.4 关键字参数
  • 四、返回值与文档说明
    • 4.1 返回多个值
    • 4.2 编写文档字符串
  • 五、函数嵌套与作用域
    • 5.1 嵌套函数示例
    • 5.2 变量作用域
    • 5.3 global关键字


一、什么是函数?

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

二、函数定义与调用

2.1 基本语法

def 函数名(参数):"""函数说明文档"""函数体return 返回值

2.2 示例演示

定义问候函数

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

调用函数

greet("Alice")  # 输出:Hello, Alice!
greet("Bob")    # 输出:Hello, Bob!

三、函数参数详解

3.1 位置参数

def calculate_area(length, width):return length * widthprint(calculate_area(5, 3))  # 输出:15

3.2 默认参数

def power(base, exponent=2):return base ** exponentprint(power(3))     # 输出:9
print(power(2, 4))  # 输出:16

3.3 可变参数

def sum_all(*numbers):total = 0for n in numbers:total += nreturn totalprint(sum_all(1, 2, 3))  # 输出:6

3.4 关键字参数

def build_profile(**info):profile = {}for key, value in info.items():profile[key] = valuereturn profileuser = build_profile(name="Alice", age=25, occupation="Engineer")
print(user)  # 输出:{'name': 'Alice', 'age': 25, 'occupation': 'Engineer'}

四、返回值与文档说明

4.1 返回多个值

def calculate(a, b):return a+b, a-b, a*bsum_result, sub_result, mul_result = calculate(8, 5)

4.2 编写文档字符串

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

五、函数嵌套与作用域

5.1 嵌套函数示例

def outer():print("外层函数被调用")def inner():print("内层函数被调用")inner()outer()

输出:
外层函数被调用
内层函数被调用

5.2 变量作用域

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

5.3 global关键字

count = 0def increment():global countcount += 1increment()
print(count)  # 输出:1

六、综合案例

def temperature_converter(value, unit):"""温度单位转换器参数:value: 温度值unit: 原始单位('C'或'F')返回:转换后的温度值(保留两位小数)"""if unit == 'C':converted = value * 9/5 + 32return round(converted, 2)elif unit == 'F':converted = (value - 32) * 5/9return round(converted, 2)else:raise ValueError("无效的温度单位")print(temperature_converter(37, 'C'))  # 输出:98.6
print(temperature_converter(100, 'F')) # 输出:37.78
http://www.lryc.cn/news/2379911.html

相关文章:

  • java collection集合特点知识点详解
  • ngx_http_realip_module 模块概述
  • 自定义CString类与MFC CString类接口对比
  • 华为OD机试真题——考勤信息(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
  • Go语言测试用例的执行与分析
  • vue3 vite 路由
  • MyBatis:动态SQL
  • 游戏引擎学习第280天:精简化的流式实体sim
  • femap许可与多用户共享
  • 王树森推荐系统公开课 排序03:预估分数融合
  • 网络I/O学习-poll(三)
  • k8s(12) — 版本控制和滚动更新(金丝雀部署理念)
  • 【git config --global alias | Git分支操作效率提升实践指南】
  • chrome源码中WeakPtr 跨线程使用详解:原理、风险与最佳实践
  • 【Go】从0开始学习Go
  • Windows 安装显卡驱动
  • 模块与包的导入
  • Google设置app-ads.txt
  • docker安装rockerMQ
  • 交叉引用、多个参考文献插入、跨文献插入word/wps中之【插入[1-3]、连续文献】
  • PLC双人舞:profinet转ethernet ip网关奏响施耐德与AB的协奏曲
  • Image and depth from a conventional camera with a coded aperture论文阅读
  • 缺乏团队建设活动,如何增强凝聚力?
  • 特征筛选方法总结
  • 力扣HOT100之二叉树:230. 二叉搜索树中第 K 小的元素
  • pinia.defineStore is not a function
  • 入职软件开发与实施工程师了后........
  • PCL点云库点云数据处理入门系列教材目录(2025年5月更新....)
  • Linux面试题集合(5)
  • python动漫论坛管理系统