Python 基础核心总结 🐍

Python 是一门简洁优雅上手极快的解释型语言,由 Guido van Rossum 于 1991 年首次发布。它以可读性极高的语法、丰富强大的标准库、活跃的开源生态闻名于世。本文将系统梳理 Python 基础知识体系,帮助你快速建立起完整的知识框架。🚀


📖 目录

  1. Python 程序运行流程
  2. 数据类型
  3. 控制流程
  4. 函数基础
  5. 面向对象基础
  6. 模块与包
  7. 异常处理
  8. 文件操作

Python 程序运行流程

解释型语言的特点

Python 属于解释型语言,代码无需提前编译,解释器(Interpreter)会逐行读取源代码,将其转换为字节码(.pyc 文件),再由 Python 虚拟机(PVM)执行。这种模式和 Java 的 JVM 有些相似,只是少了显式的编译步骤。

执行方式一览

方式 命令 说明
交互式 python / python3 每行输入即执行,适合学习和调试
脚本式 python script.py 将代码写入文件后一次性运行
编译字节码 python -m py_compile script.py 预编译生成 .pyc 文件,加快导入速度

💡 小贴士:Python 3 的解释器命令通常用 python3,部分系统上 python 默认指向 Python 2。


数据类型

基本数据类型

Python 内置了丰富的基本数据类型,无需额外声明,直接赋值即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 整数
age = 25

# 浮点数
height = 1.75

# 字符串
name = "Alice"
message = 'Hello, Python!'

# 布尔值
is_student = True
is_empty = False

# 空值
result = None

# 查看数据类型
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(name)) # <class 'str'>

常用容器类型

📋 列表(List)

列表是 Python 最常用的有序可变容器,类似其他语言的数组,但功能强大得多:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 创建列表
fruits = ["apple", "banana", "orange"]
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]

# 添加元素
fruits.append("grape") # 末尾添加
fruits.insert(0, "mango") # 指定位置插入

# 删除元素
fruits.remove("banana") # 按值删除
popped = fruits.pop() # 弹出末尾元素

# 切片
print(fruits[0]) # 第一个元素
print(fruits[-1]) # 最后一个元素
print(fruits[1:3]) # 切片:索引1到2
print(fruits[::2]) # 步长2

# 列表推导式
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

🔒 元组(Tuple)

元组与列表类似,但不可变,适合存储固定数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 创建元组
point = (3, 4)
colors = ("red", "green", "blue")

# 单元素元组(必须加逗号)
single = (42,)

# 解包
x, y = point
a, b, c = colors

# 常用方法
print(colors.index("red")) # 0
print(colors.count("blue")) # 1

🔑 集合(Set)

集合用于存储无序唯一的元素,自动去重:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 创建集合
skills = {"Python", "Java", "Go", "Python"}
print(skills) # {'Python', 'Java', 'Go'} 自动去重

# 集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 & set2) # {3, 4} 交集
print(set1 | set2) # {1, 2, 3, 4, 5, 6} 并集
print(set1 - set2) # {1, 2} 差集
print(set1 ^ set2) # {1, 2, 5, 6} 对称差集

# 添加 / 删除
skills.add("Rust")
skills.discard("Java") # 安全删除,不存在不报错
skills.remove("Go") # 删除,不存在抛异常

📖 字典(Dict)

字典是键值对(Key-Value)的无序容器,查找效率接近 O(1):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 创建字典
person = {
"name": "Alice",
"age": 25,
"city": "Shanghai"
}

# 访问
print(person["name"]) # Alice
print(person.get("age", 0)) # 25,默认值

# 添加 / 修改
person["email"] = "alice@example.com"
person["age"] = 26

# 删除
del person["city"]
popped = person.pop("email")

# 遍历
for key, value in person.items():
print(f"{key}: {value}")

for key in person.keys():
print(key)

for value in person.values():
print(value)

# 字典推导式
squares_dict = {x: x**2 for x in range(5)}

数据类型全家福


控制流程

条件判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
score = 85

if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "D"

print(f"成绩等级: {grade}")

# 三元表达式
result = "及格" if score >= 60 else "不及格"

循环结构

🔄 for 循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 基本语法
for i in range(5):
print(i) # 0 1 2 3 4

# 遍历列表
animals = ["cat", "dog", "bird"]
for animal in animals:
print(animal)

# 带索引
for index, animal in enumerate(animals):
print(f"{index}: {animal}")

# 遍历字典
user = {"name": "Bob", "age": 30}
for key, value in user.items():
print(f"{key} = {value}")

🔁 while 循环

1
2
3
4
5
6
7
8
9
10
11
12
13
count = 0
while count < 5:
print(count)
count += 1
else:
print("循环正常结束") # else 在循环正常结束时执行

# 无限循环 + break
while True:
response = input("输入 'quit' 退出: ")
if response == "quit":
break
print(f"你输入了: {response}")

控制跳转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# break: 跳出当前循环
for i in range(10):
if i == 5:
break
print(i) # 0 1 2 3 4

# continue: 跳过当前迭代
for i in range(5):
if i == 2:
continue
print(i) # 0 1 3 4

# pass: 占位符,不做任何操作
for i in range(5):
if i == 2:
pass # TODO: 稍后实现
else:
print(i)

函数基础

函数定义与调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 基本函数
def greet(name):
"""问候函数,返回问候语"""
return f"Hello, {name}!"

message = greet("Alice")
print(message) # Hello, Alice!

# 默认参数
def power(base, exponent=2):
return base ** exponent

print(power(3)) # 9,使用默认值
print(power(2, 3)) # 8,显式指定

# 可变参数 *args
def sum_all(*numbers):
total = 0
for n in numbers:
total += n
return total

print(sum_all(1, 2, 3, 4, 5)) # 15

# 关键字参数 **kwargs
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")

print_info(name="Bob", age=30, city="Beijing")

函数返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 无返回值(默认返回 None)
def print_hello():
print("Hello!")

# 单返回值
def square(x):
return x * x

# 多返回值(返回元组)
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder

q, r = divide(10, 3)
print(f"商={q}, 余数={r}") # 商=3, 余数=1

特殊函数特性

Lambda 表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# lambda: 匿名函数,适合简短函数
square = lambda x: x ** 2
print(square(5)) # 25

# 配合内置函数使用
numbers = [1, 2, 3, 4, 5]
filtered = list(filter(lambda x: x % 2 == 0, numbers))
print(filtered) # [2, 4]

mapped = list(map(lambda x: x * 2, numbers))
print(mapped) # [2, 4, 6, 8, 10]

sorted_list = sorted(numbers, key=lambda x: -x) # 降序排列
print(sorted_list) # [5, 4, 3, 2, 1]

装饰器

装饰器可以在不修改原函数的前提下,为函数添加额外功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import time

def timer(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

@timer
def slow_function():
time.sleep(1)
return "Done"

print(slow_function())
# slow_function 执行耗时: 1.0012秒
# Done

函数调用流程


面向对象基础

类与对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Dog:
"""狗类"""

# 类属性(所有实例共享)
species = "犬科"

def __init__(self, name, age):
"""初始化方法"""
self.name = name # 实例属性
self.age = age

def bark(self):
"""叫声方法"""
return f"{self.name} 汪汪叫!"

def get_info(self):
return f"{self.name}, {self.age}岁"

def __str__(self):
"""字符串表示"""
return f"Dog({self.name})"

# 创建实例
dog1 = Dog("旺财", 3)
dog2 = Dog("小白", 1)

print(dog1.bark()) # 旺财 汪汪叫!
print(dog2.get_info()) # 小白, 1岁
print(Dog.species) # 犬科
print(dog1) # Dog(旺财)

继承与多态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
raise NotImplementedError("子类必须实现此方法")

class Cat(Animal):
def speak(self):
return f"{self.name} 喵~"

class Dog(Animal):
def speak(self):
return f"{self.name} 汪!"

# 多态:同一接口,不同实现
animals = [Cat("咪咪"), Dog("旺财")]
for animal in animals:
print(animal.speak())
# 咪咪 喵~
# 旺财 汪!

访问控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class User:
def __init__(self, username, password):
self.username = username # 公有属性
self.__password = password # 私有属性(名称重整)

def check_password(self, pwd):
return self.__password == pwd

@property
def password(self):
"""属性访问器,只读"""
return "******"

user = User("alice", "secret123")
print(user.username) # alice
print(user.password) # ******
print(user.check_password("secret123")) # True

# print(user.__password) # AttributeError: 访问不到!

类层次结构


模块与包

模块基础

Python 的模块就是一个 .py 文件。以下是标准库中的常用模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 导入整个模块
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0

# 导入特定成员
from random import randint, choice
print(randint(1, 10)) # 1~10 随机整数
print(choice(["a", "b", "c"])) # 随机选一个

# 导入并起别名
import datetime as dt
now = dt.datetime.now()
print(now) # 2026-05-27 11:45:00.xxx

# 导入所有(不推荐)
from math import *

常用标准库一览

模块 用途 示例
os 操作系统接口 os.getcwd(), os.listdir()
sys 系统参数 sys.path, sys.argv
datetime 日期时间 datetime.datetime.now()
json JSON 处理 json.dumps(), json.loads()
re 正则表达式 re.match(), re.findall()
collections 集合容器 Counter, defaultdict
itertools 迭代工具 count(), cycle()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 实战示例:os 和 pathlib
import os
from pathlib import Path

# 当前目录
cwd = Path.cwd()
print(cwd)

# 遍历目录
for item in cwd.iterdir():
print(item.name)

# 路径拼接
file_path = cwd / "data" / "example.txt"
print(file_path.exists())

# collections 计数器
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counter = Counter(words)
print(counter.most_common(2)) # [("apple", 3), ("banana", 2)]

包的结构

一个典型的 Python 包结构如下:

1
2
3
4
5
6
7
mypackage/
├── __init__.py # 包初始化文件
├── module1.py # 模块1
├── module2.py # 模块2
└── subpackage/
├── __init__.py
└── module3.py
1
2
3
4
5
6
# __init__.py 中可以指定默认导出
# from .module1 import Something

# 使用包
# from mypackage import module1
# module1.do_something()

异常处理

基本结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try:
num = int(input("输入一个整数: "))
result = 10 / num
print(f"10 / {num} = {result}")
except ValueError:
print("输入无效,请输入整数!")
except ZeroDivisionError:
print("除数不能为零!")
except Exception as e:
print(f"未知错误: {e}")
else:
print("全部执行成功,没有异常")
finally:
print("无论是否出错,都会执行")

主动抛出异常

1
2
3
4
5
6
7
8
9
def divide(a, b):
if b == 0:
raise ZeroDivisionError("除数不能为0")
return a / b

try:
result = divide(10, 0)
except ZeroDivisionError as e:
print(e) # 除数不能为0

自定义异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class ValidationError(Exception):
"""自定义验证异常"""
def __init__(self, field, message):
self.field = field
self.message = message
super().__init__(f"{field}: {message}")

def validate_age(age):
if age < 0:
raise ValidationError("age", "年龄不能为负数")
if age > 150:
raise ValidationError("age", "年龄不合理")
return True

try:
validate_age(-5)
except ValidationError as e:
print(e) # age: 年龄不能为负数

异常处理流程


文件操作

读写文本文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 读取文件
with open("example.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部
# content = f.readline() # 读取一行
# content = f.readlines() # 读取所有行到列表

# 写入文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("第一行内容\n")
f.write("第二行内容\n")

# 追加模式
with open("log.txt", "a", encoding="utf-8") as f:
f.write("新的日志记录\n")

JSON 文件处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import json

# 写入 JSON
data = {
"name": "Alice",
"age": 25,
"skills": ["Python", "Java", "Go"]
}

with open("user.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)

# 读取 JSON
with open("user.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["name"]) # Alice

文件操作安全要点

⚠️ 最佳实践:始终使用 with open(...) as f: 语句,它可以确保文件在使用完毕后自动关闭,即使中途发生异常也不会遗漏。


总结 🎯

以上我们梳理了 Python 的核心基础知识:

模块 核心要点
运行流程 解释执行,.py → 字节码 → PVM
数据类型 基本类型 + 四大容器(list/tuple/set/dict)
控制流程 if/elif/else + for/while + break/continue/pass
函数 def 定义、默认参数、*args、**kwargs、lambda、装饰器
面向对象 类、继承、多态、访问控制(私有属性)
模块 import/from、常用标准库、pip 安装三方库
异常处理 try/except/else/finally、自定义异常
文件操作 with open、读写文本、JSON 处理

Python 的设计哲学是:简洁优于复杂、明了优于隐晦。掌握这些基础后,你已经具备了继续深入 Web 开发、数据分析、人工智能等方向的核心能力。🚀

🐍 “Simple is better than complex” —— The Zen of Python


如果你有任何问题,欢迎留言交流!