CA6000 AI Programming
Topic 1 目录
- Python 简介
- Python 输入/输出
- 变量、常量与注释
- 数据类型与类型转换
- 字符串与字符串操作
- 条件执行(if / elif / else / match-case)
- 循环结构(while / for)
- 关键控制语句:break、continue、pass
- 整体总结
1️⃣ Python 简介
Python 是一种简单易学、广泛用于 AI/ML 的语言 。
Python 特点:
- 语法简单,接近英文
- 拥有大量 AI/数据科学相关库
- 跨平台
- 社区庞大
- AI/DS 领域多数开发都用 Python
两种版本:
- Python 2(已过时)
- Python 3.x(必须使用此版本)
2️⃣ Python 输入 / 输出(I/O)
✔ 输出(print 函数)
示例:
print("Hello world")
功能:将字符串输出到屏幕上 。
解释:
- print() 是函数,用于显示内容。
- 输入后直接执行。
✔ 输入(input 函数)
示例:
name = input("What is your name? ")
print("Hello " + name)
解释:
input()接收用户输入,返回值是字符串类型。- 输入的值存入变量
name。 - print 再输出拼接后的结果。
3️⃣ 变量、常量、注释
✔ 变量(Variables)
变量是用于存储数据的容器。Python 不需要提前声明类型。
示例:
a = "Hello World!"
b = 2 + 3
解释:
- a 自动变成字符串变量。
- b 自动变成整数变量。
- Python 的变量类型会随着赋值改变。
再次示例:
a = 7
a = "hello again"
解释:
变量类型可以随时改变(int → str)。
✔ 变量命名规则
变量名必须:
- 以字母或
_开头 - 不能以数字开头
- 只能包含字母、数字和
_ - 区分大小写
示例:
myName = "Nick" # CamelCase
my_name = "Nick" # snake_case
✔ 常量(Constants)
常量示例:
PI = 3.14159
MAX_MARK = 100
FILE_NAME = "test1.csv"
特点:
- 约定俗成:全部大写+下划线
- 用于“不会改变”的值。
✔ 注释(Comments)
单行注释:
# this is a comment
多行注释(docstring):
'''
Line 1
Line 2
'''
用途:解释代码、暂时禁用代码、做说明文档。
4️⃣ Python 数据类型(Data Types)
常见内置数据类型:
- str:字符串
- int, float:数字
- bool:True / False
- list, tuple, set, range:序列
- dict:字典(键值对)
示例:
stringx = "apple"
floatx = 3.14
boolx = True
listx = ["apple", "banana"]
tuplex = ("apple", "banana")
setx = {"apple", "banana"}
rangex = range(6)
dictx = {"name": "John", "age": 36}
✔ 类型转换(Casting)
示例:
a = int(7.1) # 7
b = str(7) # "7"
c = float(7) # 7.0
d = list(("apple", "banana"))
检查变量类型:
print(type(a))
print(type(b))
✔ input() 类型转换
因为 input 默认返回字符串,因此需要转换:
x = float(input("Key in first number"))
y = float(input("Key in second number"))
print(x + y)
解释:
- 这是数字加法,不是字符串拼接。
✔ 原地操作(In-place Operation)
示例:
x = 1
x = x + 1 # 常见写法
x += 1 # 原地操作,等价
其他示例:
*=/=%=**=(次方)
5️⃣ 字符串(String)
✔ 字符串是字符序列(可索引)
示例:
text = "Hello World!"
print(text[2]) # 输出 "l"
print(text[2:5]) # "llo"
print(text[:5]) # "Hello"
print(text[1:]) # "ello World!"
解释:Python 字符串支持切片(slice)。
✔ 常用字符串方法
示例:
text = "Hello World!"
len(text)
text.upper()
text.lower()
text.isupper()
text.islower()
text.find("Wo")
✔ 去除空白:strip()
a = " Hello World "
print(a.strip()) # "Hello World"
✔ format() 格式化字符串
age = 22
txt = "My name is Chen, and I am {}"
print(txt.format(age))
解释:
txt是一个包含占位符{}的字符串。txt.format(age)会将age变量的值(这里是 22)替换掉{},从而生成完整的字符串My name is Chen, and I am 22并打印出来。
可以有多个占位符,并用多个参数替换它们。举个例子:
txt = "My name is {} and I am {} years old."
name = "Alice"
age = 30
print(txt.format(name, age))
输出:
My name is Alice and I am 30 years old.
这种格式化方法在处理动态文本和输出时非常有用,能让字符串的生成更具可读性和灵活性。
✔ 反斜杠 \(转义字符)
示例:
txt = 'It\'s alright.\n'
print(txt)
换行:\n
转义单引号:\'
6️⃣ 条件执行(Conditional Execution)
✔ if 语句
示例:
a = 38
b = 24
if a > b:
print("a is greater than b")
布尔表达式:>、<、==、!= 等。
✔ if – elif – else
if a > b:
print("a > b")
elif a == b:
print("a == b")
else:
print("a < b")
也可以使用逻辑 and:
if a > b and c > a:
print("Both conditions are True")
✔ match-case(Python 3.10 起支持)
character = 'A'
match character:
case 'A':
print("character is A")
case 'B':
print("character is B")
用途:对比多种情况,比 if-elif 更整洁。
7️⃣ 循环(Loops)
✔ while 循环
i = 1
while i < 6:
print(i)
i = i + 1
解释:满足条件时重复执行。
✔ 无限循环 + break
i = 1
while True:
print(i)
if i == 3:
break
i += 1
print("done")
解释:
while True永远循环break跳出循环
✔ continue 跳过当前循环
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
输出:1,2,4,5,6(跳过3)
✔ for 循环(遍历序列)
range 版本:
for x in range(10):
print(x)
带起始与步长:
for x in range(3, 10):
print(x)
for x in range(2, 30, 3):
print(x)
遍历字符串:
for x in "apple":
print(x)
✔ 使用占位变量 _
在 Python 中,_ 常常用作一个占位符变量,特别是当你不打算使用这个变量时。在循环或其他结构中,如果你不需要循环变量的值,可以使用 _ 来代替它。这不仅清晰地表达了你不打算使用该变量,还能避免产生不必要的命名警告。
for _ in range(3):
print("Hello World!")
在上面的代码中,_ 表示循环变量在这次循环中不会被使用,只是单纯地重复执行 print("Hello World!") 三次。
8️⃣ pass 语句
pass 是一个占位语句,它用于在代码块中暂时不执行任何操作,通常用于占位或者作为未完成代码的占位符。当你需要写一个语法上有效的代码块,但又不想在某个阶段实际执行任何操作时,pass 就非常有用了。
for x in [0, 1, 2]:
pass
在上面的代码中,pass 语句表示这个 for 循环没有实际的操作,只是占据了位置。这种情况可能出现在你编写代码时,暂时还没有想好具体的逻辑,或者需要保持代码结构完整,但不执行任何操作。
总结:
_用于表示你不关心的变量。pass用于占位,表示目前没有实现的代码块。
9️⃣ PDF 第 1 章总结要点:
- 基本输入输出
- 变量
- 数据类型
- 条件执行:if / while / for
- break、continue、pass
Topic 2 目录
- Python 内建数据结构概览
- List(列表)
- 列表特性
- 创建方法、访问方式、修改方式
- 添加、插入、删除、排序、遍历
- 方法总表
- 例子逐行解释 - Tuple(元组)
- 特性、创建、访问
- 不可变性质、如何绕开不可变
- 常用方法
- 例子解释 - Dictionary(字典)
- 特性、键值对访问
- keys, values, items
- 修改、增加、删除
- 嵌套字典
- 字典推导式
- 例子解释 - Set(集合)
- 特性、唯一性、无序性
- 添加、合并、更新
- 集合的数学操作(并、交、差)
- 例子解释 - 四种数据结构总结对比
1️⃣ Python 内建数据结构概览
Python 提供四种常用数据结构,用来存储多个数据元素:
| 数据结构 | 符号 | 是否有序 | 是否可修改 | 是否可重复 | 特点 |
|---|---|---|---|---|---|
| List | [] |
✔ 有序 | ✔ 可修改 | ✔ 可重复 | 使用最广,灵活 |
| Tuple | () |
✔ 有序 | ✘ 不可修改 | ✔ 可重复 | 安全、快速 |
| Dictionary | {key:value} |
✔(3.7 后有序) | ✔ 可修改 | ✘ 键不可重复 | 键值对存储 |
| Set | {} |
✘ 无序 | ✔ 可修改 | ✘ 不可重复 | 自动去重、集合操作 |
2️⃣ List(列表)
✔ 列表特性
- 使用
[]创建 - 可以包含不同类型的元素
- 有序(保持插入顺序)
- 可修改:增删改都可以
- 可以有重复元素
➤ 列表的创建
fruits = ["apple", "banana", "cherry", "durian"]
mixed = ["apple", 2, "cherry"]
分析:
fruits是字符串列表mixed是混合类型列表(Python 允许)
➤ 列表访问(索引)
fruits = ["apple", "banana", "cherry", "durian"]
print(fruits[1]) # banana
print(fruits[-1]) # durian(倒数第一)
print(fruits[1:3]) # ["banana", "cherry"]
解释:
fruits[1]:第二个元素fruits[-1]:最后一个元素fruits[1:3]:切片,从 1 到 2(不含 3)
➤ 检查元素是否存在
if "cherry" in fruits:
print("'cherry' is in the fruits list")
➤ 添加与插入
fruits.append("orange") # 末尾添加
fruits.insert(1, "pineapple") # 在位置 1 插入
➤ 修改元素
fruits[1] = "orange" # 替换一个
fruits[1:3] = ["pineapple", "orange"] # 替换两个
fruits[1:2] = ["mango", "peach"] # 用两个替换一个
➤ 排序
fruits.sort()
➤ 合并列表
fruits.extend(local_fruits)
➤ 删除元素
fruits.remove("cherry") # 按值删
fruits.pop(2) # 按索引删除
✔ 列表方法总表(PDF 原文)
| 方法 | 说明 |
|---|---|
| append() | 尾部添加 |
| clear() | 清空列表 |
| copy() | 复制 |
| count() | 某值出现次数 |
| extend() | 合并列表 |
| index() | 找到值的位置 |
| insert() | 插入 |
| pop() | 删除并返回元素 |
| remove() | 删除指定值 |
| reverse() | 反序 |
| sort() | 排序 |
⭐ Finger Exercise – 例子解释
代码:
fruits = []
for _ in range(3):
fruits.append(input("Name a fruit: "))
print(fruits)
for fruit in sorted(fruits):
print(fruit)
逐行解释:
fruits = []建立空列表for _ in range(3):循环 3 次;_表示不关心变量名- 每次
input()获取用户输入并放入列表 sorted()返回排序后的新列表- 最后逐行打印水果名
3️⃣ enumerate() 函数
将列表变成 “(索引, 值)” 形式的可迭代对象。
例子:
fruits = ["apple", "banana", "cherry"]
enu_fruits = enumerate(fruits, 10)
for index, item in enu_fruits:
print(index)
print(item)
解释:
enumerate(fruits, 10):从索引 10 开始- 每轮循环返回
(index, value) - 输出:
10 apple
11 banana
12 cherry
4️⃣ List Comprehension(列表推导式)
普通写法:
new_list = []
for x in fruits:
if "a" in x:
new_list.append(x)
推导式:
new_list = [x for x in fruits if "a" in x]
5️⃣ Tuple(元组)
特性
- 使用
() - 不可修改(immutable)
- 可包含不同类型
- 访问方式与列表一样
例子:
fruits = ("apple", "banana", "cherry", "banana")
➤ 常用方法
fruits.count("banana")
fruits.index("banana")
➤ 元组不可变,但可绕过:
this_tuple = ("apple", "banana", "cherry")
y = list(this_tuple) # 转列表
y.remove("apple")
this_tuple = tuple(y) # 转回元组
6️⃣ Dictionary(字典)
➤ 基本用法
car = {"brand": "BYD", "model": "SEAL", "year": 2024}
print(car["model"])
➤ 查看 keys、values、items
car.keys()
car.values()
car.items()
➤ 修改、增加
car["year"] = 2025
car["color"] = "RED"
➤ 删除
car.pop("model")
➤ 嵌套字典
cars = {
"car_1": {"brand": "Toyota", "model": "Corolla", "year": 2010},
"car_2": {"brand": "Mazda", "model": "CX5", "year": 2018}
}
print(cars["car_1"]["model"])
➤ 字典推导式
fruits = ["apple", "banana", "cherry"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
7️⃣ Set(集合)
特性
{}表示- 无序、不重复
- 自动去重
例子:
this_set = {"apple", "banana", "cherry", "banana"}
输出将自动去掉重复值。
➤ 集合运算
Set_1 = {1, 2, 3, 4}
Set_2 = {2, 3, 5, 6}
Set_1 | Set_2 # 并集
Set_1 & Set_2 # 交集
Set_1 - Set_2 # 差集
🔚 最终总结对比
| 数据结构 | 优点 | 缺点 | 典型用途 |
|---|---|---|---|
| List | 灵活,可改,可重复 | 操作速度比 tuple 慢 | 收集任意数据 |
| Tuple | 不可变、安全、快 | 不能改 | 配置、固定数据 |
| Dictionary | 键值对结构清晰 | 键必须唯一 | 表示对象、资料结构 |
| Set | 自动去重、数学集合 | 无序、不能索引 | 唯一值、交并差 |
Topic 3 目录
讲解 Python 函数(Functions) 的所有基础与进阶概念,包括:
- 什么是函数、为什么使用函数
- 内建函数的使用方式
- 如何自定义函数
- 函数命名规范
- 参数(parameters)与参数传递(arguments)
- 默认参数、多参数、可变数量参数
- 全局变量、作用域(scope)
- 函数定义顺序
- 返回值、格式化返回
- 类型注解(Type annotation)
- Docstring 与 help()
- Generator(生成器)
- Lambda(匿名函数)
- Decorator(装饰器)
内容偏向 Python 编程基础,是理解 AI 应用开发之前必须掌握的 Python 核心知识。
什么是函数 Function
函数是一段 只有被调用(call) 才会执行的代码。
主要优点:
- 让代码可重用
- 结构更清晰
- 方便维护
示例:内建函数 print、input、len、sorted… 已经是函数。
print() 的格式化与参数
示例:
name = "Nick"
print("Hello", name) # 两个参数
print("Hello " + name) # 一个参数
❗ 两种方式不同:
- 第一种:print 内多个参数会用空格分隔
- 第二种:字符串拼接 → 只有一个参数
print() 的更多参数
end=
改变 print 结尾的内容:
print("Hello", end=", ")
print("how are you today?")
输出:
Hello, how are you today?
sep=
改变参数之间的分隔符:
print("Brand", "Honda", sep=":")
输出:
Brand:Honda
创建自定义函数(def)
基本结构:
def my_function():
print("Hello from a function")
调用方式:
my_function()
注意:缩进决定函数内部代码的范围
函数命名规范
- 可使用字母、数字、下划线
- 最佳实践:使用 snake_case
get_input()
- 单下划线开头
_internal_function()通常表示“内部使用”
向函数传入参数
示例:
def greeting(to):
print(f"Hello {to} ! ")
name = input("What is your name?\n")
greeting(name)
- argument:调用时给的值(name)
- parameter:函数定义中的接收者(to)
参数可为任何类型
def type_of_food(food):
for x in food:
print(x)
fruits = ["Apple", "Banana", "Durian"]
type_of_food(fruits)
这里传入的是 list。
无返回值的函数也称为 Procedure 过程。
默认参数 & 多参数
默认参数:
def greeting(to="World"):
print(f"Hello {to} ! ")
greeting() # 打印 Hello World
greeting("Nick") # 打印 Hello Nick
多参数:
def greeting(msg="Hello", to="world"):
print(f"{msg}, {to} ! ")
可变数量参数(*args)
如果参数个数不确定:
def greeting(*names):
for name in names:
print(f"Good day {name} !")
greeting("Nick", "Jess", "Alex")
*names 收集所有参数成为一个 tuple。
共享变量:global 关键字
示例:
RUN = 0
STOP = 1
game = RUN
def check():
global game
game = STOP
关键点:
- global 让函数可以修改外部变量
- 不推荐大量使用,但某些情境(状态控制)会用到
变量作用域(scope)
Python 变量有 4 种作用域:
- Local(函数内部)
- Enclosing(嵌套函数外层)
- Global(全局)
- Built-in
三个示例分别展示:
示例 1:使用到全局变量
x = 'global'
def outer():
print(x)
输出 global。
示例 2:内部使用 enclosing:
x = 'global'
def outer():
x = 'enclosing'
def inner():
print(x)
inner()
输出 enclosing。
示例 3:local 覆盖:
x = 'global'
def outer():
x = 'enclosing'
def inner():
x = 'local'
print(x)
inner()
输出 local。
函数定义顺序
可以将所有函数写在 main 下面;只要在调用前定义即可。
示例:
def main():
greeting_1("Nick")
greeting_2("Alex")
def greeting_1(name):
print(f"Hello, {name} !")
def greeting_2(name):
print(f"Good Day, {name} !")
main()
返回值 return
示例:
def multiply(a, b):
value = a * b
return value
return 将数据返回给调用者。
返回格式化字符串
def introduce(name, age):
return f"Hello, I am {name}, and I am {age} years old."
类型注解(Type Annotation)
让代码更易读:
def my_func(a: str, b: int) -> float:
...
a: str⇒ 参数 a 应为 string-> float⇒ 返回值为 float
Docstring 与 help()
使用三引号写函数说明:
def calculate_area(length: float, width: float) -> float:
"""
Calculates the area of a rectangle.
Args:
length ...
width ...
Returns ...
"""
return length * width
help(calculate_area)
help() 会打印 docstring 内容。
Generator(生成器)与 yield
生成器使用 yield 一次返回一个值,不会终止函数。
示例:
def generator():
yield "Alex"
yield "Brian"
yield "Cindy"
优点:
- 节省内存
- 适合处理大数据量或无限序列
Lambda 匿名函数
把简单函数写成一行:
mac = lambda x, y: (x * y) + x
print(mac(3, 4))
等价于:
def mac(x, y):
return (x * y) + x
lambda 结合 filter()
用于筛选数据:
number_list = [1, 12, 13, 24, 35, 38, 47]
odd_numbers = filter(lambda x: x % 2 != 0, number_list)
print(list(odd_numbers))
筛选出所有奇数。
Decorator(装饰器)
装饰器使用 @ 符号,为函数添加额外功能。
示例:避免除以 0:
def guard_zero(func):
def wrapper(x, y):
if y == 0:
print("Cannot divide by 0.")
return
return func(x, y)
return wrapper
@guard_zero
def divide(x, y):
return x / y
调用 divide(10, 0) 时,会先执行 guard_zero。
总结
- 函数让代码更容易维护与复用
- Python 提供许多强大函数相关工具:
- Generator
- Lambda
- Decorator
Topic 4 (Modules and Packages)
1. Python 模块 (Modules)
模块是包含常用功能的代码库。Python 自带了许多内置模块,供开发者使用。
示例:导入模块
import time
import random
通过 import 关键字导入 Python 的标准库模块。这样就可以使用模块中的所有函数和对象。
查看模块中的所有函数和变量
dir(random)
使用 dir() 函数可以查看模块中包含的所有函数和变量。
2. 使用模块中的特定函数
如果只需要使用模块中的某个函数,可以选择性导入:
示例:
from random import choice as ch
for _ in range(10):
print(ch(["red", "green", "blue"]))
from random import choice as ch:从random模块中导入choice函数,并为它取一个别名ch。- 这样可以节省内存,因为只导入了需要的函数,而不是整个模块。
3. 创建自定义模块
您也可以创建自己的模块,保存自己定义的函数。这样,当程序变得很大时,可以将不同的功能拆分到不同的文件中,方便管理。
示例:
- 创建
my_module.py:
def greeting1(name):
print(f"Hello, {name} !")
def greeting2(name):
print(f"Good Day, {name} !")
- 在程序文件中导入并使用:
import my_module
my_module.greeting1("Nick")
my_module.greeting2("Alex")
这样,您就创建了一个简单的模块 my_module.py,并在另一个程序中导入和调用它。
4. 测试模块
在开发模块时,通常需要测试模块的功能,而不必依赖于另一个程序来导入它。可以在模块中加入 if __name__ == "__main__" 来实现当模块作为独立脚本运行时进行测试。
示例:
def main():
greeting1("test1")
greeting2("test2")
def greeting1(name):
print(f"Hello, {name} !")
def greeting2(name):
print(f"Good Day, {name} !")
if __name__ == "__main__":
main()
if __name__ == "__main__":这个条件确保了只有当模块被直接运行时,main()函数才会执行。如果模块是被其他程序导入的,则不会执行main()。
5. 正则表达式模块 (re)
Python 提供了 re 模块用于正则表达式操作,允许用户根据特定模式查找字符串中的字符序列。
示例:
import re
text = "That cloth is very nice"
match = re.search("^That.*nice$", text)
if match:
print("matched!")
^That表示字符串以 "That" 开头。.*表示任意字符,出现 0 次或多次。nice$表示字符串以 "nice" 结尾。
6. 密码强度检测功能
我们可以利用正则表达式编写一个函数,要求用户输入符合要求的强密码。
示例:
from re import search
def strong_password():
while True:
password = input("Enter a strong password: ")
if len(password) < 8:
print("Password should be at least 8 characters long.")
elif search("[a-z]", password) == None:
print("Password should have at least one lowercase letter.")
elif search("[A-Z]", password) == None:
print("Password should have at least one uppercase letter.")
elif not search("[0-9]", password):
print("Password should have at least one number.")
elif not search("[!@#$%^&*()]", password):
print("Password should have at least one special character.")
else:
print("Strong password set.")
break
- 该函数要求密码至少包含 8 个字符,至少一个小写字母、一个大写字母、一个数字以及一个特殊字符(如
!@#$%^&*())。
7. 第三方库和包
包和库是指由第三方提供的代码文件,它们包含多个模块,帮助我们实现更复杂的功能。pandas 和 numpy 等是常见的 Python 包。
- 包(Package)是包含多个模块的文件夹。
- 库(Library)是包含多个包的文件集合。
安装第三方库
可以使用 pip 或 conda 命令来安装第三方库:
pip install pandas
安装后,可以在程序中通过 import 来使用库中的模块和功能:
import pandas
8. 使用 Conda 安装包
conda 是一个用于安装 Python 包的工具,通常用于 Anaconda 环境。
示例:
- 安装包时,
conda默认从 Anaconda 的主仓库下载包,但也可以指定其他仓库(如conda-forge)。
总结
- 模块:Python 内置的功能库,包含可直接使用的函数和对象。
- 自定义模块:可以将自定义函数保存为
.py文件,方便复用。 - 正则表达式:通过
re模块,用户可以处理文本中的模式匹配。 - 包与库:第三方提供的代码集合,通过
pip或conda安装并使用。
Topic 6
主要介绍了Python中的文件处理,涵盖了文件的读写操作、CSV文件处理、JSON文件处理等内容。下面是该PDF中每个部分的详细中文教程和代码解释。
1. Python文件处理
Python提供了多种内置函数来处理文件,包括创建、读取、更新和删除文件。最常用的函数是 open(),用于打开一个文件并返回一个文件对象。
示例:创建和写入文件
file = open("example.txt", "w") # 创建文件或覆盖文件
file.write("Hello, World!") # 写入内容
file.close() # 关闭文件
open()的第一个参数是文件名,第二个参数是模式。"w"模式用于写入,如果文件不存在,会创建文件。- 记得使用
close()关闭文件,以确保写入的内容被保存。
2. 文件读取
read() 方法
用于一次性读取文件的全部内容。
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
readline() 方法
逐行读取文件内容。
file = open("example.txt", "r")
line = file.readline() # 读取一行
print(line)
file.close()
逐行循环读取文件
file = open("example.txt", "r")
for line in file:
print(line)
file.close()
for line in file会逐行读取文件。
3. 文件写入
w模式:覆盖文件内容,文件不存在时创建新文件。a模式:在文件末尾追加内容。
file = open("example.txt", "a")
file.write("Appended text.")
file.close()
4. 使用 with 语句自动关闭文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 文件自动关闭,不需要显式调用 file.close()
5. 文件操作模式总结
"r":以读取模式打开文件。"w":以写入模式打开文件(文件不存在则创建,存在则覆盖)。"a":以追加模式打开文件(文件不存在则创建,存在则在末尾添加内容)。"r+":以读写模式打开文件。"w+":以读写模式打开文件,文件内容会被清空。"a+":以读写模式打开文件,文件内容会追加。
6. CSV文件处理
CSV(Comma Separated Values)是一种常见的存储数据的文本格式。
示例CSV文件内容(cars.csv)
id,brand,model,year,color
1,Mazada,CX5,2014,red
2,VW,Jetta,2018,silver
3,Honda,Civic,2022,white
使用 csv.reader 读取CSV文件
import csv
file = open("cars.csv")
cars = csv.reader(file)
header = next(cars) # 读取表头
print(header)
rows = []
for row in cars:
print(row)
rows.append(row)
file.close()
- 使用
csv.reader逐行读取CSV内容,next()用于读取第一行表头。
使用 csv.DictReader 将每行转换为字典
import csv
cars = csv.DictReader(open("cars.csv"))
for row in cars:
print(row)
- 每一行会被转换成字典,键是列名,值是对应的内容。
7. JSON文件处理
JSON(JavaScript Object Notation)是一种常见的文本数据格式,广泛用于客户端和服务器之间传输数据。
示例JSON数据
{
"brand": "Mazada",
"model": "CX5",
"year": 2014,
"color": "red"
}
使用 json.loads() 解析JSON字符串
import json
x = '{"brand":"Mazada", "model":"CX5", "year":2014, "color":"red"}'
y = json.loads(x)
print(f'Model = {y["model"]}')
print(f'Year = {y["year"]}')
json.loads()将JSON字符串转换为Python字典。
8. 总结
通过本教程,你可以掌握Python中关于文件操作的基础知识,包括如何读取、写入文件,处理CSV和JSON格式的数据等。理解并灵活运用文件操作对于处理存储和数据交换非常重要。
Topic 7
Python错误处理教程
1. 错误类型
Python中有两种主要的错误类型:
- 语法错误 (Syntax Error):程序因代码错误无法运行。
- 运行时/逻辑错误 (Runtime/Logic Error):程序运行时出现的错误,通常是由于程序未能预见到用户的输入或操作。
2. 异常处理(try-except)
Python通过 try 和 except 语句来捕获并处理在程序执行过程中出现的错误。
- try:用于测试代码块是否有错误。
- except:用于处理在
try代码块中出现的错误。
示例:
try:
print(x)
except:
print("something goes wrong!")
解释:这里我们试图打印变量 x,如果 x 没有定义,会抛出异常,except 块捕获该异常并打印错误信息。
3. 常见的内置异常
Python有许多内置的异常类,常见的有:
- NameError:当变量未定义时抛出。
- ValueError:当值无效时抛出。
- KeyError:当字典中没有指定的键时抛出。
4. 使用 try-except 处理异常
在实际应用中,我们可以使用 try-except 来处理错误。例如,当用户输入一个无效值时:
try:
n = int(input("Enter a value: "))
print(f"Value is {n}")
except ValueError:
print("Please enter the value properly")
except:
print("something goes wrong!")
解释:这段代码尝试将用户输入的值转换为整数,如果输入无效(如字母或符号),会捕获 ValueError 异常并提示用户。
5. 使用 else
else 语句在没有异常发生时执行。它通常与 try-except 一起使用,确保只有在没有错误时才执行某些操作。
try:
n = int(input("Enter a value: "))
except ValueError:
print("Please enter the value properly")
except:
print("something goes wrong!")
else:
print(f"Value is {n}")
解释:如果没有错误发生,else 块将打印输入的值。
6. 使用 finally
finally 语句块会在 try-except 后无论是否发生异常都会执行。通常用于释放资源(如关闭文件、数据库连接等)。
try:
n = int(input("Enter a value: "))
except ValueError:
print("Please enter the value properly")
except:
print("something goes wrong!")
else:
print(f"Value is {n}")
finally:
print("try-except completed")
解释:即使发生异常或没有发生异常,finally 块中的内容都会执行。它通常用于清理操作。
7. 文件操作中的错误处理
当操作文件时,可能会遇到打开文件、读取文件、写入文件等错误。可以通过 try-except 来捕获这些错误:
try:
f = open("file.txt")
try:
f.write("Hello")
except:
print("Something goes wrong when writing to file")
finally:
f.close()
except:
print("something goes wrong when opening the file")
解释:首先尝试打开文件,如果文件不存在或权限问题,捕获异常并输出错误信息;然后尝试写入文件,如果出错,也会捕获异常。
8. 使用 assert 进行调试
assert 语句用于检查条件是否为真。如果条件为假,程序会抛出 AssertionError 异常并停止执行。通常用于调试阶段验证程序的正确性。
assert 5+10 == 15 # 这行代码不会抛出异常
assert 5+10 == 12, "This is not correct" # 这行代码会抛出异常并提示错误信息
解释:assert 用于验证表达式的正确性。如果表达式为 False,则会抛出错误并提供错误信息。
9. 类型化异常
Python还提供了其他类型的异常,可以通过不同的异常类型来处理不同的错误情境。例如 ValueError、KeyError、IndexError 等。
10. 性能分析(Software Profiling)
性能分析用于优化程序的运行效率。例如,使用 time 模块来测量代码的执行时间。
import time
def main():
t1 = time.perf_counter()
# 调用某个函数
t2 = time.perf_counter()
print(f"Execution time: {t2 - t1} seconds")
解释:time.perf_counter() 返回高精度的时间,用于测量代码执行的时间差,从而帮助分析性能瓶颈。
11. 示例代码:sleep 与 add 函数的性能分析
import time
def sleep():
time.sleep(1)
def add():
total = 0
for a in range(100_000_000):
total += a
def main():
for function in [sleep, add]:
t1 = time.perf_counter()
function()
t2 = time.perf_counter()
print(f"{function.__name__}() execution time: {t2 - t1} seconds")
main()
解释:这个例子展示了如何使用 time.perf_counter() 来测量不同函数的执行时间。sleep 函数模拟了一个暂停,而 add 函数则执行了大量的加法操作。

浙公网安备 33010602011771号