Python 基础:函数与模块
3.1 函数定义
python
# 基本函数
def greet(name):
"""打招呼函数"""
return f"Hello, {name}!"
# 默认参数
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!
# 可变参数
def sum_all(*args):
"""求和"""
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 15
# 关键字参数
def person_info(name, age, city):
return f"{name}, {age}岁, 住在{city}"
print(person_info(age=25, name="Alice", city="Beijing")) # 关键字参数顺序无关1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
3.2 Lambda 表达式
python
# lambda 匿名函数
square = lambda x: x ** 2
print(square(5)) # 25
# 配合内置函数使用
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_nums = sorted(numbers, reverse=True)
print(sorted_nums) # [9, 5, 4, 3, 2, 1, 1]
# 按绝对值排序
nums = [-5, 3, -2, 8]
sorted_nums = sorted(nums, key=abs)
print(sorted_nums) # [-2, 3, -5, 8]1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
3.3 模块导入
python
# 标准导入
import math
print(math.sqrt(16)) # 4.0
# 指定别名
import numpy as np
import pandas as pd
# 从模块导入特定内容
from datetime import datetime, timedelta
from pathlib import Path
# 导入并起别名
from requests import get as http_get1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
3.4 模块创建
python
# mymodule.py
def add(a, b):
return a + b
PI = 3.14159
# __all__ 控制 from module import * 的导出内容
__all__ = ['add', 'PI']
# main.py
from mymodule import add, PI
print(add(1, 2)) # 3
print(PI) # 3.141591
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
3.5 包
mypackage/
├── __init__.py # 包初始化
├── module1.py
├── module2.py
└── subpackage/
├── __init__.py
└── module3.py1
2
3
4
5
6
7
2
3
4
5
6
7
python
# 导入
from mypackage import module1
from mypackage.subpackage import module31
2
3
2
3
[[返回 Python 首页|python/index]]