sync from local backup

This commit is contained in:
chunyu
2026-08-05 23:59:15 +08:00
commit d48ec1747c
358 changed files with 34384 additions and 0 deletions
+83
View File
@@ -0,0 +1,83 @@
# 第4章 函数与模块
## 4.1 函数定义
```python
def greet(name):
"""函数的文档字符串"""
return f"你好,{name}!"
msg = greet("张三")
print(msg) # 你好,张三!
```
### 参数类型
```python
# 默认参数
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9
print(power(2, 3)) # 8
# 可变参数
def total(*numbers):
result = 0
for n in numbers:
result += n
return result
```
---
## 4.2 变量作用域
```python
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
```
---
## 4.3 匿名函数
```python
square = lambda x: x ** 2
print(square(5)) # 25
```
---
## 4.4 模块导入
```python
import math
print(math.pi)
import random
print(random.randint(1, 100))
```
### 常用标准库
| 模块 | 用途 |
|------|------|
| `os` | 操作系统接口 |
| `json` | JSON处理 |
| `datetime` | 日期时间 |
| `random` | 随机数 |
---
## 本章练习
1. 编写一个函数,计算列表中所有元素的平均值
2. 编写一个函数,统计字符串中每个字符出现的次数
3. 编写一个模块,包含计算圆面积、矩形面积的函数