1.递归深度错误:递归调用的深度过大,导致递归错误。
- # 示例
- import sys
- sys.setrecursionlimit(10000) # 增加递归深度限制
-
- def factorial(n):
- if n == 0:
- return 1
- else:
- return n * factorial(n-1)
-
- result = factorial(5000) # 错误,递归深度超出默认限制
错误结果: 递归深度错误会导致Python解释器抛出RecursionError,程序崩溃。
修改错误的方式: 增加递归深度限制(不建议,因为可能会导致栈溢出),或者使用迭代替代递归来计算阶乘。
2. 线程死锁:两个线程相互等待对方释放锁,导致程序停滞。
- # 示例
- import threading
-
- lock1 = threading.Lock()
- lock2 = threading.Lock()
-
- def task1():
- with lock1:
- with lock2:
- print("Task 1")
-
- def task2():
- with lock2:
- with lock1:
- print("Task 2")
-
- t1 = threading.Thread(target=task1)
- t2 = threading.Thread(target=task2)
-
- t1.start()
- t2.start()
- t1.join()
- t2.join()
错误结果: 两个线程都无法继续执行,程序永远无法完成。
修改错误的方式: 避免循环依赖锁,或者使用超时机制来解除死锁。
3. 内存泄漏:未正确释放不再使用的内存。
- # 示例
- class MyClass:
- def __init__(self):
- self.data = [0] * 1000000
-
- obj_list = []
- for _ in range(1000):
- obj = MyClass()
- obj_list.append(obj) # 未释放 obj 占用的内存
错误结果: 内存占用逐渐增加,最终导致内存耗尽。
修改错误的方式: 明确删除不再需要的对象引用,或者使用垃圾回收来管理内存。
4. 多线程竞争条件:多个线程同时访问和修改共享数据,导致不可预测的结果。
- # 示例
- import threading
-
- counter = 0
-
- def increment():
- global counter
- for _ in range(1000000):
- counter += 1
-
- thread1 = threading.Thread(target=increment)
- thread2 = threading.Thread(target=increment)
-
- thread1.start()
- thread2.start()
-
- thread1.join()
- thread2.join()
-
- print("Counter:", counter) # 可能不是预期的结果
-
错误结果: counter 的值可能小于期望值(2000000)。
修改错误的方式: 使用锁(例如threading.Lock())来确保在同一时刻只有一个线程能够修改 counter。
5.浮点数比较错误:由于浮点数精度问题,两个看似相等的浮点数无法正确比较。
- # 示例
- a = 0.1 + 0.2
- b = 0.3
-
- print(a == b) # 错误,由于浮点数精度问题,结果可能为False
错误结果: a == b 的比较结果可能是 False。
修改错误的方式: 使用math模块中的isclose函数进行浮点数比较,或者比较它们的差值是否在可接受的范围内。
6.文件未关闭错误:打开文件但未在使用完毕后关闭它,导致资源泄漏。
- # 示例
- file = open("example.txt", "r")
- data = file.read()
- # 操作文件数据
- # 忘记关闭文件
-
错误结果: 程序可能无法释放文件资源,导致其他操作无法访问该文件。
修改错误的方式: 使用with语句确保文件在使用后自动关闭,或者显式调用file.close()方法。
7.逻辑错误:代码逻辑错误导致程序无法按预期工作。
- # 示例
- def calculate_discount(price, discount_percentage):
- discount = price * (discount_percentage / 100)
- discounted_price = price - discount
- return discount
-
- price = 100
- discount_percentage = 20
- actual_discount = calculate_discount(price, discount_percentage)
-
- print("Discounted price:", price - actual_discount) # 错误,计算折扣而非折扣金额
错误结果: 输出的折扣价格不正确。
修改错误的方式: 修改calculate_discount函数返回折扣金额而不是折扣率。
8.无限循环错误:循环条件设置不当导致无法退出循环。
- # 示例
- count = 0
-
- while count < 10:
- print("Infinite Loop") # 错误,未更新count的值
错误结果: 程序陷入无限循环,永远无法停止。
修改错误的方式: 在循环中确保更新count的值,使循环条件最终为False。