给前端的 Python 基础速查手册

64 阅读2分钟

1. 变量与数据类型

# 动态类型,赋值即定义变量
x = 10              # int
pi = 3.14           # float
name = "Alice"      # str
flag = True         # bool

# 主要数据结构
lst = [1, 2, 3]               # list(可变有序)
tpl = (1, 2, 3)               # tuple(不可变有序)
dct = {"key": "value"}        # dict(键值对映射)
st = {1, 2, 3}                # set(无序唯一元素)

2. 元组(Tuple)

tpl = (10, 20, 30)
print(tpl[0])         # 10,支持索引和切片
print(tpl[1:3])       # (20, 30)
# tpl[0] = 100        # 错误,元组不可变

3. 集合(Set)

st = {1, 2, 3, 3}     # 自动去重,输出 {1, 2, 3}
st.add(4)             # 添加元素
st.remove(2)          # 删除元素
print(3 in st)        # True

# 集合运算
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b)          # 交集 {3}
print(a | b)          # 并集 {1, 2, 3, 4, 5}
print(a - b)          # 差集 {1, 2}

4. 字典(Dict)

d = {"name": "Alice", "age": 25}
print(d["name"])          # Alice
print(d.get("gender"))    # None,避免KeyError
print(d.get("gender", "F"))  # 设置默认值

# 遍历字典
for key in d:
    print(key, d[key])

for key, value in d.items():
    print(key, value)

5. 条件判断与循环

# 条件语句
if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

# for循环遍历列表
for item in lst:
    print(item)

# 带索引遍历
for i, val in enumerate(lst):
    print(i, val)

# while循环
count = 0
while count < 3:
    print(count)
    count += 1

6. 函数与参数

def add(a, b=0):
    return a + b

result = add(5, 3)
print(result)

# 多返回值
def get_pos():
    return 10, 20

x, y = get_pos()
print(x, y)

# 可变参数
def func(*args, **kwargs):
    print(args)      # 元组形式的位置参数
    print(kwargs)    # 字典形式的关键字参数

func(1, 2, a=3, b=4)

7. 异常处理

try:
    x = 1 / 0
except ZeroDivisionError as e:
    print("Error:", e)
finally:
    print("Always execute")

8. 列表、字典、集合推导式

# 列表推导式
squares = [x*x for x in range(5)]

# 字典推导式
square_dict = {x: x*x for x in range(5)}

# 集合推导式
square_set = {x*x for x in range(5)}

9. 文件操作

# 读文件
with open('data.txt', 'r') as f:
    content = f.read()

# 写文件
with open('output.txt', 'w') as f:
    f.write("Hello, world!")

10. 模块导入

import math
print(math.sqrt(16))

from datetime import datetime
print(datetime.now())

11. 类与对象

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, I am {self.name}, {self.age} years old")

p = Person("Alice", 25)
p.greet()

12. 其他重要特性

12.1 生成器

def gen():
    for i in range(5):
        yield i*i

for val in gen():
    print(val)

12.2 Lambda匿名函数

add = lambda x, y: x + y
print(add(3, 4))  # 7

12.3 上下文管理(with)

with open('file.txt', 'r') as f:
    content = f.read()

12.4 类型注解

def greet(name: str) -> str:
    return "Hello, " + name