Python作为当前最流行的编程语言之一,其语法设计以简洁优雅著称。我最初接触Python时,最让我惊讶的是它用缩进来表示代码块的方式——这与其他语言使用大括号{}的惯例完全不同。经过多年使用,我发现这种设计反而让代码更易读和维护。
Python3在2008年发布,相比Python2做了许多改进,特别是统一了字符串编码(默认使用Unicode),修正了整数除法等问题。现在Python2已经停止维护,新项目都应该使用Python3。下面我将从最基础的语法元素开始,带你系统掌握Python3的核心语法要点。
Python是动态类型语言,声明变量时不需要指定类型。但理解数据类型对编程至关重要:
python复制# 基本数据类型示例
name = "张三" # 字符串(str)
age = 25 # 整数(int)
price = 19.99 # 浮点数(float)
is_active = True # 布尔值(bool)
Python3中有几个重要的数据类型特性:
注意:Python变量名区分大小写,且不能以数字开头。推荐使用下划线命名法(如user_name)
Python支持常见的算术、比较和逻辑运算符:
python复制# 算术运算符
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.333... (真正的除法)
print(10 // 3) # 3 (整除)
print(10 % 3) # 1 (取模)
print(10 ** 3) # 1000 (幂运算)
# 比较运算符
print(10 > 3) # True
print(10 == 3) # False
print(10 != 3) # True
# 逻辑运算符
print(True and False) # False
print(True or False) # True
print(not True) # False
Python还有一个特殊的赋值运算符:=(海象运算符),可以在表达式中赋值:
python复制if (n := len("hello")) > 3:
print(f"长度{n}大于3")
Python的控制结构非常直观,完全依赖缩进来定义代码块:
python复制age = 18
if age < 12:
print("儿童")
elif age < 18:
print("青少年")
else:
print("成人")
Python中没有switch语句,可以使用字典或if-elif链替代。
python复制# for循环
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(f"我喜欢吃{fruit}")
# while循环
count = 0
while count < 5:
print(count)
count += 1
Python的循环支持else子句,当循环正常结束(非break中断)时执行:
python复制for i in range(3):
print(i)
else:
print("循环完成")
函数是Python组织代码的基本单元:
python复制def greet(name, greeting="你好"):
"""打招呼的函数
Args:
name: 人名
greeting: 问候语,默认为'你好'
"""
return f"{greeting}, {name}!"
print(greet("张三")) # 你好, 张三!
print(greet("李四", "Hello")) # Hello, 李四!
Python函数有几个重要特性:
提示:函数应该保持单一职责原则,每个函数只做一件事
Python使用try-except块处理异常:
python复制try:
age = int(input("请输入年龄: "))
print(f"明年你将{age + 1}岁")
except ValueError:
print("请输入有效的数字!")
finally:
print("程序执行完毕")
常见的异常类型包括:
列表推导式是Python中非常强大的特性,可以简洁地创建列表:
python复制# 传统方式
squares = []
for x in range(10):
squares.append(x**2)
# 列表推导式
squares = [x**2 for x in range(10)]
还可以加入条件判断:
python复制even_squares = [x**2 for x in range(10) if x % 2 == 0]
类似的还有字典推导式和集合推导式:
python复制# 字典推导式
square_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 集合推导式
unique_lengths = {len(x) for x in ["apple", "banana", "cherry"]}
# {5, 6}
生成器表达式与列表推导式类似,但使用圆括号,并且惰性求值:
python复制sum_of_squares = sum(x**2 for x in range(1000000)) # 不占用大量内存
lambda用于创建匿名函数:
python复制# 普通函数
def square(x):
return x ** 2
# lambda函数
square = lambda x: x ** 2
lambda常用于需要函数作为参数的场景,如sorted的key参数:
python复制students = [{"name": "张三", "score": 88},
{"name": "李四", "score": 92}]
sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)
装饰器是修改函数行为的强大工具:
python复制def log_time(func):
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
@log_time
def calculate():
time.sleep(1)
calculate() # 会自动打印执行时间
装饰器的常见用途包括:
Python是完全面向对象的语言,一切皆对象:
python复制class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"你好,我是{self.name},今年{self.age}岁"
p = Person("张三", 25)
print(p.greet())
类的基本要点:
__init__是构造函数python复制class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def greet(self):
return f"我是学生{self.name},学号{self.student_id}"
s = Student("李四", 20, "2023001")
print(s.greet()) # 重写了父类的方法
Python支持多重继承,但应谨慎使用(可能导致"菱形继承"问题)。
通过实现特殊方法可以自定义类的行为:
python复制class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
常用的特殊方法包括:
__str__:定义对象的字符串表示__len__:定义长度__getitem__/__setitem__:实现索引访问__iter__:使对象可迭代Python文件就是一个模块,使用import导入:
python复制# 导入整个模块
import math
print(math.sqrt(16)) # 4.0
# 导入特定函数
from math import sqrt, pi
print(sqrt(9)) # 3.0
# 给模块起别名
import numpy as np
包是包含__init__.py文件的目录:
code复制my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
导入包中的模块:
python复制from my_package import module1
from my_package.subpackage import module3
Python内置了大量实用的模块:
python复制# 文件操作
import os
import shutil
# 系统功能
import sys
import subprocess
# 数据处理
import json
import csv
# 日期时间
from datetime import datetime, timedelta
# 正则表达式
import re
Python社区遵循PEP 8风格指南,主要规则包括:
可以使用工具自动检查:
bash复制pip install flake8
flake8 your_script.py
python复制if True:
print("hello") # IndentationError
python复制x = 10
def func():
print(x) # 可以读取
x = 20 # UnboundLocalError
python复制def add_item(item, items=[]): # 默认参数只计算一次
items.append(item)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] 不是预期的[2]
正确做法:
python复制def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
python复制# 慢
result = []
for item in items:
result.append(str(item))
# 快
result = list(map(str, items))
python复制# 慢
if x in [1, 2, 3]: # 每次都要创建列表
# 快
if x in {1, 2, 3}: # 集合查找是O(1)
python复制def read_large_file(file_path):
with open(file_path) as f:
for line in f:
yield line
for line in read_large_file("huge_file.txt"):
process(line)
python复制if (n := len(data)) > 10:
print(f"数据量过大: {n}项")
python复制def func(a, b, /, c, d, *, e, f):
pass
func(1, 2, 3, d=4, e=5, f=6) # a,b必须位置参数,e,f必须关键字参数
python复制match point:
case (0, 0):
print("原点")
case (0, y):
print(f"Y轴上,y={y}")
case (x, 0):
print(f"X轴上,x={x}")
case (x, y):
print(f"({x}, {y})")
case _:
print("不是二维点")
一个规范的Python项目通常这样组织:
code复制my_project/
├── README.md
├── setup.py
├── requirements.txt
├── src/
│ └── my_package/
│ ├── __init__.py
│ ├── module1.py
│ └── subpackage/
├── tests/
│ ├── __init__.py
│ └── test_module1.py
├── docs/
│ └── conf.py
└── .gitignore
使用venv创建隔离的Python环境:
bash复制python -m venv venv
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
pip install -r requirements.txt
bash复制pip install black
black your_script.py
bash复制pip install mypy
mypy your_script.py
python复制# test_sample.py
def test_addition():
assert 1 + 1 == 2
def test_subtraction():
assert 3 - 1 == 2
运行测试:
bash复制pip install pytest
pytest test_sample.py
bash复制pip install sphinx
sphinx-quickstart docs
python复制import csv
from collections import defaultdict
def process_sales_data(input_file, output_file):
sales = defaultdict(float)
with open(input_file) as f:
reader = csv.DictReader(f)
for row in reader:
sales[row["product"]] += float(row["amount"])
with open(output_file, "w") as f:
writer = csv.writer(f)
writer.writerow(["product", "total_sales"])
for product, total in sales.items():
writer.writerow([product, round(total, 2)])
if __name__ == "__main__":
process_sales_data("sales.csv", "sales_report.csv")
python复制import requests
from typing import Dict, Any
def get_weather(city: str, api_key: str) -> Dict[str, Any]:
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(url)
response.raise_for_status()
return response.json()
def display_weather(data: Dict[str, Any]) -> None:
temp = data["main"]["temp"] - 273.15 # 开尔文转摄氏度
print(f"当前温度: {temp:.1f}°C")
print(f"天气状况: {data['weather'][0]['description']}")
if __name__ == "__main__":
api_key = "your_api_key" # 实际使用时替换
data = get_weather("Beijing", api_key)
display_weather(data)
python复制import concurrent.futures
import time
def task(name, duration):
print(f"任务{name}开始")
time.sleep(duration)
print(f"任务{name}完成")
return f"结果{name}"
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
futures = {
executor.submit(task, "A", 2),
executor.submit(task, "B", 1),
executor.submit(task, "C", 3)
}
for future in concurrent.futures.as_completed(futures):
print(future.result())
这个例子展示了Python的线程池用法,适合I/O密集型任务。对于CPU密集型任务,可以考虑使用ProcessPoolExecutor。
官方文档:
在线学习平台:
书籍推荐:
社区资源:
进阶主题:
python复制# Python2
print "hello"
# Python3
print("hello")
python复制# Python2
3 / 2 # 1
# Python3
3 / 2 # 1.5
3 // 2 # 1
python复制# Python2
type("hello") # str (字节串)
type(u"hello") # unicode
# Python3
type("hello") # str (Unicode)
type(b"hello") # bytes
使用更高效的数据结构:
利用内置函数和库:
使用JIT编译器:
编写C扩展:
Python使用引用计数和垃圾回收机制管理内存:
引用计数:
垃圾回收:
手动触发垃圾回收:
python复制import gc
gc.collect()
多线程:
多进程:
协程:
text复制flask==2.0.1
requests>=2.25.0
bash复制pip install pipenv
pipenv install flask
pipenv shell
bash复制pip install poetry
poetry init
poetry add flask
bash复制conda create -n myenv python=3.8
conda activate myenv
conda install numpy