Python 语法速查手册

2026-06-25 · 阅读 10 分钟 · Python基础

← 返回首页

变量与数据类型

# 变量赋值
name = "Python"
version = 3.11
is_awesome = True
nothing = None

# 多重赋值
x, y, z = 1, 2, 3

# 类型检查
print(type(name))  # <class 'str'>
print(type(version))  # <class 'float'>

字符串操作

# 字符串格式化
name = "World"
print(f"Hello, {name}!")  # f-string (推荐)
print("Hello, {}!".format(name))  # format 方法

# 常用方法
text = "  Hello, Python!  "
print(text.strip())       # "Hello, Python!"
print(text.lower())       # "  hello, python!  "
print(text.upper())       # "  HELLO, PYTHON!  "
print(text.replace("Python", "World"))  # "  Hello, World!  "
print(text.split(","))    # ['  Hello', ' Python!  ']

列表推导式

# 基础列表推导式
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

# 嵌套列表推导式
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)  # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

# 字典推导式
word = "hello"
char_count = {c: word.count(c) for c in set(word)}
print(char_count)  # {'h': 1, 'e': 1, 'l': 2, 'o': 1}

# 集合推导式
unique_lengths = {len(word) for word in ["hello", "world", "python"]}
print(unique_lengths)  # {5, 6}

字典操作

# 创建字典
person = {
    "name": "张三",
    "age": 25,
    "city": "北京"
}

# 获取值
print(person.get("name"))       # "张三"
print(person.get("phone", "N/A"))  # "N/A" (默认值)

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

# 字典推导式
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

函数

# 基础函数
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("World"))           # "Hello, World!"
print(greet("World", "Hi"))     # "Hi, World!"

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

flexible(1, 2, 3, name="Python", version=3.11)
# 位置参数: (1, 2, 3)
# 关键字参数: {'name': 'Python', 'version': 3.11}

# Lambda 函数
add = lambda x, y: x + y
print(add(3, 5))  # 8

# 高阶函数
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4]

装饰器

# 基础装饰器
def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} 执行时间: {end - start:.4f} 秒")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(1)
    return "完成"

slow_function()

# 带参数的装饰器
def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(times=3)
def say_hello():
    print("Hello!")

say_hello()  # 会打印 3 次 "Hello!"

生成器

# 生成器函数
def fibonacci(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b

# 使用生成器
for num in fibonacci(100):
    print(num, end=" ")
# 输出: 0 1 1 2 3 5 8 13 21 34 55 89

# 生成器表达式
squares_gen = (x**2 for x in range(10))
print(next(squares_gen))  # 0
print(next(squares_gen))  # 1
print(list(squares_gen))  # [4, 9, 16, 25, 36, 49, 64, 81]

类与面向对象

class Animal:
    def __init__(self, name, sound):
        self.name = name
        self.sound = sound
    
    def speak(self):
        return f"{self.name} says {self.sound}!"
    
    def __repr__(self):
        return f"Animal('{self.name}', '{self.sound}')"

class Dog(Animal):
    def __init__(self, name):
        super().__init__(name, "Woof")
    
    def fetch(self, item):
        return f"{self.name} fetches the {item}"

# 使用
dog = Dog("Buddy")
print(dog.speak())        # "Buddy says Woof!"
print(dog.fetch("ball"))  # "Buddy fetches the ball"

异常处理

# 基础异常处理
try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零!")
except Exception as e:
    print(f"发生错误: {e}")
finally:
    print("总是执行")

# 自定义异常
class CustomError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

def check_value(value):
    if value < 0:
        raise CustomError("值不能为负数")
    return value

try:
    check_value(-1)
except CustomError as e:
    print(e)  # "值不能为负数"

上下文管理器

# 使用 with 语句
with open('file.txt', 'w') as f:
    f.write("Hello, World!")

# 自定义上下文管理器
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        import time
        self.end = time.time()
        print(f"执行时间: {self.end - self.start:.4f} 秒")

with Timer():
    import time
    time.sleep(1)
小贴士: Python 3.10+ 引入了 match-case 语句(模式匹配),这是一种更强大的条件判断方式。

总结

掌握这些 Python 核心语法将帮助你编写更简洁、高效的代码。建议在实际项目中多加练习,逐步掌握每个特性的使用场景。