一、Python基础语法与数据类型
1. 变量与命名规则
Python变量无需声明类型,直接通过赋值创建。命名需遵循以下规则:
- 以字母或下划线开头,后接字母、数字或下划线
- 区分大小写(如
count与Count不同) - 避免使用Python保留字(如
if、for)
# 合法变量示例user_name = "Alice"_temp_var = 100# 非法变量示例# 123var = 10 # 错误:不能以数字开头# class = "Math" # 错误:class是保留字
2. 核心数据类型
| 数据类型 | 示例 | 关键特性 |
|---|---|---|
| 整数 | 42, -7 |
无大小限制 |
| 浮点数 | 3.14, -0.001 |
默认精度15-16位 |
| 布尔值 | True, False |
区分大小写 |
| 字符串 | "Hello", 'Python' |
支持单双引号,不可变 |
| 列表 | [1, 2, 3] |
可变,支持混合类型 |
| 元组 | (1, "a") |
不可变,可哈希 |
| 字典 | {"name": "Bob"} |
键必须为不可变类型 |
| 集合 | {1, 2, 3} |
无序不重复,支持集合运算 |
操作示例:
# 列表操作nums = [1, 2, 3]nums.append(4) # 添加元素nums[1] = 20 # 修改元素# 字典操作user = {"name": "Alice", "age": 25}user["email"] = "alice@example.com" # 添加键值对
二、控制结构与流程管理
1. 条件语句
Python通过缩进(通常4空格)定义代码块,支持if-elif-else链式判断:
score = 85if score >= 90:print("A")elif score >= 80:print("B") # 此处会执行else:print("C")
2. 循环结构
- for循环:遍历可迭代对象
```python
for i in range(5): # 生成0-4的序列
print(i)
fruits = [“apple”, “banana”]
for fruit in fruits:
print(fruit.upper())
- **while循环**:条件控制循环```pythoncount = 0while count < 3:print(f"Count: {count}")count += 1
- 循环控制:
break:立即终止循环continue:跳过当前迭代else:循环正常结束时执行(未被break中断)
for num in range(1, 6):if num == 3:continueif num == 6:breakprint(num)else:print("Loop completed") # 仅当未执行break时输出
三、函数与模块化编程
1. 函数定义与调用
def calculate_area(radius, pi=3.14):"""计算圆形面积Args:radius: 半径pi: 圆周率(默认值)Returns:面积值"""return pi * radius ** 2area = calculate_area(5) # 使用默认pi值
关键特性:
- 参数传递:支持位置参数、关键字参数、默认参数
- 返回值:可返回多个值(实际为元组)
- 作用域:局部变量优先于全局变量
2. 模块与包管理
-
导入方式:
import math # 导入整个模块from math import sqrt # 导入特定函数from math import * # 导入所有内容(不推荐)
-
自定义模块:
-
创建
my_module.py文件:def greet(name):return f"Hello, {name}!"
-
在其他文件中导入:
import my_moduleprint(my_module.greet("Alice"))
-
-
包结构:
my_package/├── __init__.py├── module1.py└── sub_package/├── __init__.py└── module2.py
四、面向对象编程基础
1. 类与对象
class Person:def __init__(self, name, age):self.name = nameself.age = agedef greet(self):return f"Hi, I'm {self.name}"# 创建实例p = Person("Alice", 30)print(p.greet()) # 输出: Hi, I'm Alice
核心概念:
__init__:构造函数self:指向实例自身的引用- 实例变量与类变量
2. 继承与多态
class Student(Person): # 继承Person类def __init__(self, name, age, student_id):super().__init__(name, age)self.student_id = student_iddef study(self):return f"{self.name} is studying"# 多态示例def show_info(obj):if isinstance(obj, Person):print(obj.greet())elif isinstance(obj, Student):print(obj.study())
五、异常处理与文件操作
1. 异常处理机制
try:result = 10 / 0except ZeroDivisionError as e:print(f"Error occurred: {e}")else:print("No errors")finally:print("Cleanup code")
常见异常类型:
ValueError:无效值(如int("abc"))TypeError:类型不匹配FileNotFoundError:文件未找到
2. 文件读写操作
- 文本文件读写:
```python
写入文件
with open(“test.txt”, “w”, encoding=”utf-8”) as f:
f.write(“Hello, Python!”)
读取文件
with open(“test.txt”, “r”) as f:
content = f.read()
print(content)
- **CSV文件处理**:```pythonimport csv# 写入CSVwith open("data.csv", "w", newline="") as f:writer = csv.writer(f)writer.writerow(["Name", "Age"])writer.writerow(["Alice", 25])# 读取CSVwith open("data.csv", "r") as f:reader = csv.reader(f)for row in reader:print(row)
六、进阶技巧与实践建议
-
代码风格规范:
- 遵循PEP 8指南(如行长不超过79字符)
- 使用
black或autopep8自动格式化
-
调试工具:
- 使用
pdb进行交互式调试 - IDE集成调试器(如PyCharm、VS Code)
- 使用
-
性能优化:
- 优先使用内置函数和库
- 避免在循环中重复创建对象
- 使用生成器处理大数据集
-
学习资源推荐:
- 官方文档:docs.python.org
- 实战项目:LeetCode算法题、Flask/Django小项目
- 社区交流:Stack Overflow、Python中文社区
本文通过系统化的知识梳理与实战案例,为Python学习者构建了从基础语法到项目实践的完整知识体系。建议读者通过”学习-编码-调试-复盘”的循环不断提升,同时关注Python生态的最新发展(如Python 3.12的性能改进)。掌握这些基础知识点后,可进一步探索数据分析、机器学习、Web开发等专项领域。