错误简介

Python 中级:面向开发者

Jasmin Ludolf

Senior Data Science Content Developer

什么是错误?

  • 违反规则的代码
  • 错误 = 异常
  • 会使程序终止!

部分 Python 异常的层级结构

1 https://docs.python.org/3/library/exceptions.html#exception-hierarchy
Python 中级:面向开发者

TypeError(类型错误)

  • 数据类型不兼容
"Hello" + 5

TypeError 输出,显示字符串和整数不能相加

Python 中级:面向开发者

ValueError(值错误)

float("Hello")

ValueError 输出,确认字符串 'Hello' 不能转换为 float

  • 值不在可接受范围内
float("2")

输出显示结果 2.0,无错误

Python 中级:面向开发者

回溯(Traceback)

回溯信息

Python 中级:面向开发者

回溯(Traceback)

回溯消息,突出显示错误类型

Python 中级:面向开发者

回溯(Traceback)

回溯消息,突出显示导致错误的代码

Python 中级:面向开发者

包中的代码

  • 包含他人编写的代码,如自定义函数
  • 称为源代码
  • pip install <package> 将源代码下载到本地环境
  • pandas 的 pd.read_csv() 在幕后执行该自定义函数的代码
Python 中级:面向开发者

来自包的回溯

# Import pandas package
import pandas as pd

# Create pandas DataFrame                 
products = pd.DataFrame({"ID": "ABC1",
                         "price": 29.99})

# Try to access the non-existent "tag" column
products["tag"]
Python 中级:面向开发者

来自包的回溯

因按不存在的列子集化 pandas DataFrame 而产生的回溯

Python 中级:面向开发者

来自包的回溯

回溯显示执行时出错的文件,以及 KeyError 错误类型

Python 中级:面向开发者

来自包的回溯

回溯中突出显示第 3803 行

Python 中级:面向开发者

来自包的回溯

回溯中突出显示 base.py

Python 中级:面向开发者

来自包的回溯

回溯中突出显示 KeyError

Python 中级:面向开发者

来自包的回溯

回溯显示我们代码中导致错误的行

Python 中级:面向开发者

来自包的回溯

回溯显示故意抛出错误的代码

Python 中级:面向开发者

来自包的回溯

回溯中突出显示 Raised

Python 中级:面向开发者

Passons à la pratique !

Python 中级:面向开发者

Preparing Video For Download...