Skip to content

Python 基础

Python 核心语法和常用编程范式速查。

数据类型

python
# 基本类型
name = "Sky"           # str
age = 25               # int
score = 95.5           # float
is_active = True       # bool

# 容器类型
fruits = ["apple", "banana", "cherry"]        # list(可变有序)
coords = (39.9, 116.4)                        # tuple(不可变有序)
unique_ids = {1, 2, 3}                        # set(无序去重)
config = {"host": "localhost", "port": 8080}  # dict(键值对)

列表推导式

python
# 基础
squares = [x ** 2 for x in range(10)]

# 带条件
evens = [x for x in range(20) if x % 2 == 0]

# 嵌套
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]

字典操作

python
d = {"name": "Sky", "age": 25}

# 安全取值
d.get("email", "未设置")  # 不存在时返回默认值

# 遍历
for key, value in d.items():
    print(f"{key}: {value}")

# 字典推导式
scores = {"math": 90, "english": 85, "physics": 92}
high = {k: v for k, v in scores.items() if v >= 90}

函数

python
# 默认参数 + 类型注解
def greet(name: str, greeting: str = "你好") -> str:
    return f"{greeting}{name}!"

# *args 和 **kwargs
def flexible(*args, **kwargs):
    print(f"位置参数: {args}")
    print(f"关键字参数: {kwargs}")

flexible(1, 2, name="Sky", role="dev")

Lambda 与高阶函数

python
# 排序
users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
users.sort(key=lambda u: u["age"])

# map / filter
nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
odds = list(filter(lambda x: x % 2 != 0, nums))

文件操作

python
# 读取文件
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()

# 写入文件
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!")

# 逐行读取
with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

异常处理

python
try:
    result = 10 / 0
except ZeroDivisionError:
    print("除零错误")
except Exception as e:
    print(f"未知错误: {e}")
else:
    print("没有异常")
finally:
    print("无论如何都执行")

常用标准库

模块用途常用函数
os文件系统os.path.join(), os.listdir()
jsonJSON 处理json.loads(), json.dumps()
datetime日期时间datetime.now(), strftime()
pathlib现代路径操作Path().exists(), .glob()
re正则表达式re.findall(), re.sub()

建议

Python 3.10+ 推荐使用 match-case 语法替代冗长的 if-elif 链。

用知识连接未来