• 容易犯且复杂的Python错误


    1.递归深度错误:递归调用的深度过大,导致递归错误

    1. # 示例
    2. import sys
    3. sys.setrecursionlimit(10000) # 增加递归深度限制
    4. def factorial(n):
    5. if n == 0:
    6. return 1
    7. else:
    8. return n * factorial(n-1)
    9. result = factorial(5000) # 错误,递归深度超出默认限制

    错误结果: 递归深度错误会导致Python解释器抛出RecursionError,程序崩溃。

    修改错误的方式: 增加递归深度限制(不建议,因为可能会导致栈溢出),或者使用迭代替代递归来计算阶乘。

    2. 线程死锁:两个线程相互等待对方释放锁,导致程序停滞。

    1. # 示例
    2. import threading
    3. lock1 = threading.Lock()
    4. lock2 = threading.Lock()
    5. def task1():
    6. with lock1:
    7. with lock2:
    8. print("Task 1")
    9. def task2():
    10. with lock2:
    11. with lock1:
    12. print("Task 2")
    13. t1 = threading.Thread(target=task1)
    14. t2 = threading.Thread(target=task2)
    15. t1.start()
    16. t2.start()
    17. t1.join()
    18. t2.join()

    错误结果: 两个线程都无法继续执行,程序永远无法完成。

    修改错误的方式: 避免循环依赖锁,或者使用超时机制来解除死锁。

    3. 内存泄漏:未正确释放不再使用的内存。

    1. # 示例
    2. class MyClass:
    3. def __init__(self):
    4. self.data = [0] * 1000000
    5. obj_list = []
    6. for _ in range(1000):
    7. obj = MyClass()
    8. obj_list.append(obj) # 未释放 obj 占用的内存

    错误结果: 内存占用逐渐增加,最终导致内存耗尽。

    修改错误的方式: 明确删除不再需要的对象引用,或者使用垃圾回收来管理内存。

    4. 多线程竞争条件:多个线程同时访问和修改共享数据,导致不可预测的结果。

    1. # 示例
    2. import threading
    3. counter = 0
    4. def increment():
    5. global counter
    6. for _ in range(1000000):
    7. counter += 1
    8. thread1 = threading.Thread(target=increment)
    9. thread2 = threading.Thread(target=increment)
    10. thread1.start()
    11. thread2.start()
    12. thread1.join()
    13. thread2.join()
    14. print("Counter:", counter) # 可能不是预期的结果

    错误结果: counter 的值可能小于期望值(2000000)。

    修改错误的方式: 使用锁(例如threading.Lock())来确保在同一时刻只有一个线程能够修改 counter

    5.浮点数比较错误:由于浮点数精度问题,两个看似相等的浮点数无法正确比较。

    1. # 示例
    2. a = 0.1 + 0.2
    3. b = 0.3
    4. print(a == b) # 错误,由于浮点数精度问题,结果可能为False

    错误结果: a == b 的比较结果可能是 False

    修改错误的方式: 使用math模块中的isclose函数进行浮点数比较,或者比较它们的差值是否在可接受的范围内。

    6.文件未关闭错误:打开文件但未在使用完毕后关闭它,导致资源泄漏。

    1. # 示例
    2. file = open("example.txt", "r")
    3. data = file.read()
    4. # 操作文件数据
    5. # 忘记关闭文件

    错误结果: 程序可能无法释放文件资源,导致其他操作无法访问该文件。

    修改错误的方式: 使用with语句确保文件在使用后自动关闭,或者显式调用file.close()方法。

    7.逻辑错误:代码逻辑错误导致程序无法按预期工作。

    1. # 示例
    2. def calculate_discount(price, discount_percentage):
    3. discount = price * (discount_percentage / 100)
    4. discounted_price = price - discount
    5. return discount
    6. price = 100
    7. discount_percentage = 20
    8. actual_discount = calculate_discount(price, discount_percentage)
    9. print("Discounted price:", price - actual_discount) # 错误,计算折扣而非折扣金额

    错误结果: 输出的折扣价格不正确。

    修改错误的方式: 修改calculate_discount函数返回折扣金额而不是折扣率。

    8.无限循环错误:循环条件设置不当导致无法退出循环。

    1. # 示例
    2. count = 0
    3. while count < 10:
    4. print("Infinite Loop") # 错误,未更新count的值

    错误结果: 程序陷入无限循环,永远无法停止。

    修改错误的方式: 在循环中确保更新count的值,使循环条件最终为False

  • 相关阅读:
    【开源】基于JAVA的校园失物招领管理系统
    Set集合
    U-Net生物医学图像分割讲解(Convolutional Networks for BiomedicalImage Segmentation)
    【ElementUI】ElementUI Tooltip 根据内容判断是否显示、文字提示自定义样式
    【由浅入深】k8s复杂问题排查进阶命令
    Linux常用命令——bunzip2命令
    Java基础常见面试题
    python:遗传算法(Genetic Algorithm,GA)求解23个测试函数
    内网渗透系列之mimikatz的使用以及后门植入
    js中let和var的区别
  • 原文地址:https://blog.csdn.net/m0_62110645/article/details/133590164