Python 基础语法示例¶

本 notebook 演示 Python 常用基础语法与结构:变量与类型、容器、控制流、函数、lambda、高阶函数、推导式、生成器、装饰器、类与 dataclass、异常、上下文管理器以及文件 I/O。每个部分先有简短中文说明,然后是可运行示例。

1) 导入与常量¶

演示常用的导入、类型注解和常量定义。

In [3]:
from dataclasses import dataclass
from contextlib import contextmanager
from typing import List, Dict, Generator, Iterable, Callable
import time, json, os

PI: float = 3.14159
greeting: str = "Hello, ChatNotes"
is_active: bool = True
count: int = 42
none_val = None
print('PI, greeting, is_active:', PI, greeting, is_active)
PI, greeting, is_active: 3.14159 Hello, ChatNotes True

2) 容器:list, tuple, set, dict¶

说明:列表可变,元组不可变,集合无序且唯一,字典为键值映射。

In [4]:
numbers: List[int] = [1, 2, 3, 4]
coords: tuple = (10.0, 20.0)
unique: set = set(numbers)
user: Dict[str, str] = {"name": "Henri", "role": "developer"}
print('numbers, coords, unique, user:', numbers, coords, unique, user)
numbers, coords, unique, user: [1, 2, 3, 4] (10.0, 20.0) {1, 2, 3, 4} {'name': 'Henri', 'role': 'developer'}

3) 控制流:if / for / while¶

演示条件判断、for 循环与 while 循环。

In [5]:
def control_flow_demo(n: int) -> None:
    if n <= 0:
        print('n is non-positive')
    elif n % 2 == 0:
        print('n is even')
    else:
        print('n is odd')
    for i in numbers:
        print(i, end=' ')
    print()  # 换行
    i = 0
    while i < 3:
        print('while:', i)
        i += 1

control_flow_demo(3)
n is odd
1 2 3 4 
while: 0
while: 1
while: 2

4) 函数:默认参数、可变参数、关键字参数、返回多个值¶

说明:Python 函数灵活,支持多种参数形式与多返回值(元组)。

In [6]:
def sum_and_mul(a: int, b: int = 2) -> (int, int):
    return a + b, a * b

def varargs_demo(*args, **kwargs):
    print('args:', args)
    print('kwargs:', kwargs)

print('sum_and_mul(5):', sum_and_mul(5))
varargs_demo(1, 2, 3, key='value')
sum_and_mul(5): (7, 10)
args: (1, 2, 3)
kwargs: {'key': 'value'}

5) lambda 与高阶函数¶

lambda 是匿名函数,高阶函数可以接收函数作为参数或返回函数。

In [7]:
square = lambda x: x * x
def apply_function(xs: Iterable[int], fn: Callable[[int], int]) -> List[int]:
    return [fn(x) for x in xs]

print('square(6):', square(6))
print('apply_function +1:', apply_function([1,2,3], lambda x: x+1))
square(6): 36
apply_function +1: [2, 3, 4]

6) 列表/字典/集合推导¶

推导式简洁表达集合转换与过滤。

In [8]:
squares = [x * x for x in range(6)]
even_squares = {x for x in squares if x % 2 == 0}
square_map = {x: x * x for x in range(6)}
print('squares, even_squares, square_map:', squares, even_squares, square_map)
squares, even_squares, square_map: [0, 1, 4, 9, 16, 25] {0, 16, 4} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

7) 生成器¶

生成器按需产生值,适合大数据或惰性计算。

In [9]:
def fib_generator(n: int) -> Generator[int, None, None]:
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

print('Fibonacci first 7:', list(fib_generator(7)))
Fibonacci first 7: [0, 1, 1, 2, 3, 5, 8]

8) 装饰器(示例:计时器)¶

装饰器用于在不修改原函数的前提下扩展函数功能。

In [10]:
def timer(fn: Callable) -> Callable:
    def wrapper(*args, **kwargs):
        start = time.time()
        result = fn(*args, **kwargs)
        end = time.time()
        print(f"[timer] {fn.__name__} took {(end - start):.6f}s")
        return result
    return wrapper

@timer
def heavy_task(n: int) -> int:
    s = 0
    for i in range(n):
        s += i
    return s

print('heavy_task result sample:', heavy_task(10000))
[timer] heavy_task took 0.000459s
heavy_task result sample: 49995000

9) 类与 dataclass¶

dataclass 自动生成构造函数等,演示类方法与静态方法。

In [11]:
@dataclass
class Person:
    name: str
    age: int = 0
    def greet(self) -> str:
        return f"Hi, I'm {self.name} and I'm {self.age} years old."
    @classmethod
    def from_dict(cls, d: Dict[str, object]) -> 'Person':
        return cls(name=d.get('name', 'unknown'), age=int(d.get('age', 0)))
    @staticmethod
    def is_adult(age: int) -> bool:
        return age >= 18

p = Person('Alice', 30)
print('Person greeting:', p.greet())
print('Is 17 adult?', Person.is_adult(17))
Person greeting: Hi, I'm Alice and I'm 30 years old.
Is 17 adult? False

10) 异常处理¶

使用 try/except/finally 来处理异常并做清理。

In [12]:
def div(a: float, b: float) -> float:
    try:
        return a / b
    except ZeroDivisionError:
        print('Caught division by zero, returning inf')
        return float('inf')
    finally:
        pass

print('Division examples:', div(10,2), div(1,0))
Caught division by zero, returning inf
Division examples: 5.0 inf

11) 上下文管理器与自定义 contextmanager¶

演示 with 语句与 contextmanager 装饰器。

In [13]:
@contextmanager
def simple_context(name: str):
    print(f'Entering context: {name}')
    try:
        yield {'name': name}
    finally:
        print(f'Exiting context: {name}')

with simple_context('demo') as ctx:
    print('Inside context, got:', ctx)
Entering context: demo
Inside context, got: {'name': 'demo'}
Exiting context: demo

12) 文件 I/O¶

读取与写入 JSON 文件示例(会在 notebook 所在目录写 demo.txt)。

In [14]:
def file_io_demo(base_dir: str) -> None:
    path = os.path.join(base_dir, 'demo.txt')
    data = {
        'pi': PI,
        'greeting': greeting,
        'numbers': numbers
    }
    with open(path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    print(f'Wrote JSON to {path}')
    with open(path, 'r', encoding='utf-8') as f:
        loaded = json.load(f)
    print('Read back:', loaded)

file_io_demo(os.getcwd())
Wrote JSON to /Users/henri/Documents/ChatNotes/demo.txt
Read back: {'pi': 3.14159, 'greeting': 'Hello, ChatNotes', 'numbers': [1, 2, 3, 4]}

结束。 可以按单元顺序运行全部代码以查看效果,或单独运行感兴趣的单元。