Python基础
高级、解释型、动态类型、面向对象的通用编程语言强调代码可读性(“可执行的伪代码”)支持多种编程范式:过程式、面向对象、函数式raise MyError("自定义错误")
·
一、Python 简介与环境搭建
1.1 Python 是什么?
- 高级、解释型、动态类型、面向对象的通用编程语言
- 强调代码可读性(“可执行的伪代码”)
- 支持多种编程范式:过程式、面向对象、函数式
1.2 安装 Python
- 官网下载:https://www.python.org/
- 推荐使用 Python 3.10+(截至 2026 年,主流为 3.11–3.13)
- 验证安装:终端输入
python --version或python3 --version
1.3 开发环境
- IDLE(自带)
- VS Code + Python 插件(推荐)
- PyCharm(专业 IDE)
- Jupyter Notebook(数据分析常用)
1.4 虚拟环境(Virtual Environment)
# 创建
python -m venv myenv
# 激活(Windows)
myenv\Scripts\activate
# 激活(macOS/Linux)
source myenv/bin/activate
# 退出
deactivate
二、基本语法与数据类型
2.1 注释
# 单行注释
"""
多行注释(实际是字符串,但常用于文档说明)
"""
'''也可以用三个单引号'''
2.2 变量与命名
- 动态类型:
x = 10→x = "hello"合法 - 命名规则:
- 只能包含字母、数字、下划线
- 不能以数字开头
- 不能是关键字(如
if,for,class) - 区分大小写
- 推荐风格:
snake_case(如user_name)
2.3 基本数据类型(Built-in Types)
表格
| 类型 | 示例 | 说明 |
|---|---|---|
int |
42 |
整数,任意精度 |
float |
3.14 |
浮点数(双精度) |
bool |
True, False |
布尔值(注意大写) |
str |
"hello" |
字符串(Unicode) |
NoneType |
None |
表示“无”或空值 |
✅ 所有变量都是对象,可通过
type(x)查看类型
2.4 类型转换
int("123") # → 123
float("3.14") # → 3.14
str(100) # → "100"
bool(0) # → False;非零为 True
bool("") # → False;非空字符串为 True
2.5 输入与输出
name = input("请输入姓名: ") # 返回字符串
print("Hello,", name)
print(f"你好,{name}!") # f-string(推荐)
2.6 运算符详解
算术运算符
表格
| 运算符 | 说明 | 示例 |
|---|---|---|
+ |
加 | 5 + 3 → 8 |
- |
减 | 5 - 3 → 2 |
* |
乘 | 5 * 3 → 15 |
/ |
除(浮点) | 5 / 2 → 2.5 |
// |
整除 | 5 // 2 → 2 |
% |
取余 | 5 % 2 → 1 |
** |
幂 | 2 ** 3 → 8 |
比较运算符
返回 True 或 False
==,!=,>,<,>=,<=
逻辑运算符
and:全真为真or:一真为真not:取反
身份与成员运算符
is/is not:判断是否为同一对象(内存地址)in/not in:判断元素是否在序列中
⚠️ 注意:
==比较值,is比较身份(如[] is [] → False)
三、核心数据结构
3.1 字符串(str)——不可变序列
创建
s1 = 'hello'
s2 = "world"
s3 = """多行
字符串"""
常用操作
len(s) # 长度
s[0], s[-1] # 索引
s[1:4] # 切片(左闭右开)
"he" in s # 成员判断
s.upper(), s.lower()
s.strip() # 去除首尾空白
s.split(',') # 按分隔符切分为列表
','.join(['a','b']) # 列表拼接为字符串
s.replace('old', 'new')
s.find('sub') # 返回索引,-1 表示未找到
格式化
# f-string(Python 3.6+,推荐)
name = "Alice"
age = 30
f"My name is {name}, I'm {age} years old."
# .format()
"Hello, {}".format(name)
# % 格式化(旧式,不推荐)
"Hello, %s" % name
3.2 列表(list)——可变、有序、允许重复
创建
lst = [1, 2, 3]
empty = []
from_range = list(range(5)) # [0,1,2,3,4]
常用方法
表格
| 方法 | 作用 |
|---|---|
.append(x) |
末尾添加一个元素 |
.extend(iter) |
添加多个元素(展开) |
.insert(i, x) |
在位置 i 插入 x |
.remove(x) |
删除第一个值为 x 的元素 |
.pop([i]) |
删除并返回索引 i 的元素(默认末尾) |
.clear() |
清空列表 |
.index(x) |
返回 x 的索引 |
.count(x) |
统计 x 出现次数 |
.sort() |
原地排序(可加 reverse=True) |
.reverse() |
原地反转 |
.copy() |
浅拷贝(等价于 lst[:]) |
切片与嵌套
lst[1:4:2] # 步长为2
lst[::-1] # 反转
matrix = [[1,2], [3,4]] # 二维列表
3.3 元组(tuple)——不可变、有序
创建
t = (1, 2, 3)
single = (5,) # 单元素元组必须加逗号
empty = ()
特性
- 不可修改(无
.append()等方法) - 支持索引、切片、解包
- 常用于函数返回多个值
python
编辑
def get_point():
return 10, 20 # 自动打包为元组
x, y = get_point() # 解包
3.4 集合(set)——无序、唯一、可变
创建
s = {1, 2, 3}
empty = set() # ❌ {} 是空字典!
常用操作
s.add(4)
s.discard(5) # 不存在不报错
s.remove(5) # 不存在会报 KeyError
# 集合运算
A = {1,2,3}
B = {3,4,5}
A | B # 并集 → {1,2,3,4,5}
A & B # 交集 → {3}
A - B # 差集 → {1,2}
A ^ B # 对称差 → {1,2,4,5}
3.5 字典(dict)——键值对映射
创建
d = {'name': 'Alice', 'age': 30}
d2 = dict(name='Bob', age=25)
empty = {}
键的要求
- 必须是 不可变类型(如
str,int,tuple) - 唯一性:重复键会覆盖
常用方法
d['name'] # 访问(KeyError 若不存在)
d.get('name', 'N/A') # 安全访问,可设默认值
d.keys() # dict_keys(['name', 'age'])
d.values() # dict_values(['Alice', 30])
d.items() # dict_items([('name', 'Alice'), ...])
d.update({'city': 'Beijing'})
d.pop('age') # 删除并返回值
d.clear()
字典推导式
{n: n**2 for n in range(5)} # {0:0, 1:1, 2:4, ...}
四、控制流程
4.1 条件语句
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
✅ Python 中
0,"",[],{},None,False均为 假值
4.2 循环语句
while 循环
i = 0
while i < 5:
print(i)
i += 1
else:
print("循环正常结束") # break 不触发
for 循环(遍历可迭代对象)
for item in [1,2,3]:
print(item)
for i in range(5): # 0~4
for i in range(1,6,2): # 1,3,5
# 遍历字典
for key in d:
for value in d.values():
for key, value in d.items():
控制关键字
break:跳出整个循环continue:跳过本次,进入下一次else:循环正常结束时执行(未被 break)
五、函数
5.1 定义与调用
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!
5.2 参数类型
表格
| 类型 | 说明 | 示例 |
|---|---|---|
| 位置参数 | 按顺序传入 | func(a, b) |
| 默认参数 | 有默认值 | def f(x=10): |
| 关键字参数 | 明确指定参数名 | f(x=5) |
| 可变位置参数 | 接收任意多位置参数 | def f(*args): |
| 可变关键字参数 | 接收任意多关键字参数 | def f(**kwargs): |
def demo(a, b=2, *args, **kwargs):
print(a, b, args, kwargs)
demo(1, 3, 4, 5, name='Alice', age=30)
# 输出: 1 3 (4, 5) {'name': 'Alice', 'age': 30}
⚠️ 参数顺序:
位置 → 默认 → *args → **kwargs
5.3 作用域(LEGB 规则)
- Local(函数内部)
- Enclosing(外层函数)
- Global(模块级别)
- Built-in(内置名称)
x = 10 # global
def outer():
x = 20 # enclosing
def inner():
nonlocal x # 修改 enclosing 的 x
x = 30
inner()
print(x) # 30
global var:在函数内修改全局变量nonlocal var:在嵌套函数中修改外层变量
5.4 匿名函数(lambda)
square = lambda x: x ** 2
add = lambda a, b: a + b
# 常用于高阶函数
nums = [1,2,3]
squares = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
5.5 高阶函数
map(func, iterable)→ 返回 map 对象(需转 list)filter(func, iterable)→ 过滤sorted(iterable, key=func, reverse=False)functools.reduce(func, iterable)(需导入)
from functools import reduce
total = reduce(lambda a, b: a + b, [1,2,3,4]) # 10
六、面向对象编程(OOP)
6.1 类与对象
class Dog:
species = "Canis lupus" # 类属性(所有实例共享)
def __init__(self, name, age): # 构造方法
self.name = name # 实例属性
self.age = age
def bark(self): # 实例方法
return f"{self.name} says woof!"
# 创建对象
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
6.2 三大特性
封装
- 用
_或__表示“私有”(约定或名称改写) __name→_ClassName__name(名称修饰)
继承
class Animal:
def speak(self):
pass
class Cat(Animal):
def speak(self):
return "Meow!"
c = Cat()
print(c.speak())
多态
- 不同子类对同一方法有不同实现
- Python 是鸭子类型(Duck Typing):“像鸭子就当鸭子”
6.3 特殊方法(魔术方法)
表格
| 方法 | 用途 |
|---|---|
__init__ |
初始化 |
__str__ |
用户友好字符串(print 时调用) |
__repr__ |
开发者友好字符串(调试用) |
__len__ |
支持 len(obj) |
__getitem__ |
支持 obj[key] |
__call__ |
使对象可调用(obj()) |
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # Vector(4, 6)
6.4 属性装饰器
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("半径不能为负")
self._radius = value
c = Circle(5)
print(c.radius) # 5
c.radius = 10 # 调用 setter
七、模块与包
7.1 模块(Module)
- 一个
.py文件就是一个模块 - 导入方式:python
import math from math import sqrt from math import sqrt as sq
7.2 包(Package)
-
包含
__init__.py的目录(Python 3.3+ 可省略,但建议保留) -
结构示例
mypackage/ __init__.py module1.py subpackage/ __init__.py module2.py -
导入:
from mypackage.module1 import func from mypackage.subpackage.module2 import Class
7.3 常用标准库
表格
| 模块 | 用途 |
|---|---|
os |
操作系统接口 |
sys |
系统相关参数 |
math |
数学函数 |
random |
随机数 |
datetime |
日期时间 |
json |
JSON 编解码 |
re |
正则表达式 |
collections |
高级容器(Counter, defaultdict, deque) |
itertools |
迭代工具 |
八、异常处理
8.1 基本结构
try:
risky_code()
except ValueError as e:
print("值错误:", e)
except (TypeError, KeyError) as e:
print("类型或键错误:", e)
else:
print("无异常,执行此块")
finally:
print("无论是否异常,都执行")
8.2 抛出异常
raise ValueError("无效输入")
8.3 自定义异常
class MyError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
raise MyError("自定义错误")
九、文件操作
9.1 打开与关闭
# 推荐使用 with(自动关闭)
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 手动关闭(不推荐)
f = open('file.txt', 'r')
f.close()
9.2 模式
表格
| 模式 | 说明 |
|---|---|
'r' |
读(默认) |
'w' |
写(覆盖原文件) |
'a' |
追加 |
'b' |
二进制模式(如 'rb') |
'+' |
读写(如 'r+') |
9.3 常用方法
f.read() # 读全部
f.readline() # 读一行
f.readlines() # 读所有行,返回列表
f.write("text")
f.writelines(["line1\n", "line2\n"])
十、高级特性(进阶基础)
10.1 推导式(Comprehensions)
# 列表推导式
squares = [x**2 for x in range(10) if x % 2 == 0]
# 字典推导式
{n: n**2 for n in range(5)}
# 集合推导式
{x for x in 'hello'} # {'h','e','l','o'}
# 生成器表达式(内存高效)
gen = (x**2 for x in range(10))
10.2 生成器(Generator)
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up_to(5):
print(num)
10.3 装饰器(Decorator)
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start:.2f}s")
return result
return wrapper
@timer
def slow_func():
time.sleep(1)
10.4 上下文管理器
class MyFile:
def __enter__(self):
print("打开资源")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("释放资源")
with MyFile() as f:
pass
10.5 类型提示(Type Hints)
from typing import List, Dict, Optional
def greet(name: str, age: int = 0) -> str:
return f"Hello {name}, age {age}"
def process(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
value: Optional[int] = None # 可为 int 或 None
十一、最佳实践与工具
- PEP 8:官方代码风格指南
- 虚拟环境:隔离项目依赖
- pip:包管理工具(
pip install requests) - requirements.txt:记录依赖
- Black / autopep8:自动格式化
- mypy:静态类型检查
- pytest:测试框架
更多推荐


所有评论(0)