Python 基础语法案例
下面这段代码可以直接复制到 .py 文件中运行,覆盖函数进阶、异常、文件操作和类型注解。
from dataclasses import dataclass
from pathlib import Path
from tempfile import TemporaryDirectory
def total(*numbers):
return sum(numbers)
def build_profile(name, **extra):
return {"name": name, **extra}
def make_multiplier(factor):
def multiply(value):
return value * factor
return multiply
def divide(a, b):
if b == 0:
raise ValueError("b must not be zero")
return a / b
@dataclass
class Student:
name: str
score: int
def passed(students: list[Student], line: int = 60) -> list[str]:
return [student.name for student in students if student.score >= line]
def file_case():
with TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "demo.txt"
path.write_text("hello\npython\n", encoding="utf-8")
with path.open("a", encoding="utf-8") as file:
file.write("file demo\n")
print(path.read_text(encoding="utf-8"))
def main():
print("var args:", total(1, 2, 3))
print("kwargs:", build_profile("Tom", age=20, city="Beijing"))
double = make_multiplier(2)
print("closure:", double(10))
for value in [2, 0]:
try:
print("divide:", divide(10, value))
except ValueError as error:
print("handled:", error)
students = [Student("Tom", 80), Student("Lucy", 95), Student("Jack", 50)]
print("passed:", passed(students))
file_case()
if __name__ == "__main__":
main()