Python 是由 Guido van Rossum 于 1989 年圣诞节期间开发,1991 年正式发布,设计目标是创造一种简洁、易读、可扩展的通用编程语言。Python 2.x 系列长期使用,但已于 2020 年停止维护,Python 3.x 成为主流,其在语法、性能、Unicode 支持方面均有改进。当前还有 PyPy(带 JIT 编译)、MicroPython(嵌入式)、Jython(Java 平台)等衍生实现。
案例:
# 安装 Python
sudo apt install python3
# 查看版本
python3 --version
Python 是一种解释型、强类型、动态语言,支持面向对象、函数式与命令式编程范式。其核心设计哲学“优雅胜于丑陋,明确优于晦涩”,体现在模块清晰、语法统一、内置强大标准库等方面,可通过 import this
查看。
案例:
import this
条件语句:if / elif / else
循环语句:for / while / break / continue
推导式:如 [x*x for x in range(10)]
生成器与 yield
with
语句用于资源管理
案例:
for i in range(5):
if i % 2 == 0:
print(f"Even: {i}")
else:
print(f"Odd: {i}")
支持多种数据类型:int
, float
, list
, dict
, str
, bool
, None
案例:
data = {
"name": "Alice",
"age": 30,
"is_admin": True
}
print(type(data), data["name"])
案例:
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "除数不能为0"
finally:
print("执行完成")
print(divide(10, 0))
案例:
from functools import reduce
squares = list(map(lambda x: x*x, range(5)))
print(squares)
案例:
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof!"
d = Dog("Buddy")
print(d.speak())
案例:
# 文件结构:
# mypackage/
# __init__.py
# module.py
# module.py
# def greet():
# return "Hello"
from mypackage import module
print(module.greet())
案例:
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
案例:
import gc
class Obj:
def __del__(self):
print("对象被销毁")
o = Obj()
del o
print(gc.collect())
案例:
import asyncio
async def say_hello():
await asyncio.sleep(1)
print("Hello async")
asyncio.run(say_hello())
案例:
with open("test.txt", "w") as f:
f.write("Hello File")
import requests
r = requests.get("https://httpbin.org/get")
print(r.status_code)
案例:
pip install numpy
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)
案例:
# config.yaml
# debug: true
import yaml
with open("config.yaml") as f:
config = yaml.safe_load(f)
print(config["debug"])
案例:
# test_sample.py
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
运行:
pytest test_sample.py
案例:
def greet(name: str) -> str:
return f"Hello, {name}"
运行:
mypy greet.py
案例:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello FastAPI"}
案例:
# 模式匹配 (Python 3.10+)
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
Python 是现代编程语言中最具生命力和通用性的语言之一。它将语法简洁性、功能丰富性与生态系统成熟度完美融合,适用于从快速脚本开发到大规模系统构建的各类场景。