作为一名程序员,您在开发软件时一定会遇到错误。 这可能包括导致意外结果的逻辑错误、违反编程语言规则引起的错误,甚至是运行程序时出现的错误,等等。 这些错误通常称为错误。
错误在每种编程语言中无处不在,无论学习或使用该语言有多么容易。
例如,在 Python 中,虽然该语言强调可读性,遵循富有表现力的语法,并且与其他编程语言相比被认为相对容易学习和使用,但在使用 Python 时您仍然无法避免编程错误。
由于错误不可避免地会出现,因此处理它们的一个好方法是了解可能发生的不同类型的错误以及它们是如何发生的。 这使您可以在编程时避免或最大限度地减少这些错误,并且还知道在它们出现时如何处理它们。
以下是您在使用该语言进行编程时可能遇到的一些常见 Python 错误:
目录
语法错误
语法错误是当您编写的代码违反了您正在使用的编程语言的规则时出现的错误。 这会导致无效的代码行。
例如,在 Python 中,当打印出一个字符串时,需要将其放在引号之间。 不这样做会导致语法错误。
当您遗漏左括号或右括号、方括号或花括号、关键字或函数名称拼写错误、流控制语句末尾的冒号遗漏或表达式中遗漏必需的运算符时,也会出现语法错误。
通常,如果您违反了有关如何编写 Python 代码的规则,就会出现语法错误。
## syntax error arising from missing quotation mark ## around the string being printed print("Hello World) age = 20 ## Syntax error arising from missing colon in an if statement if age > 18 print("Age is over 18") ## Syntax error because '(' was never closed def square(x: return x * x print(square(4))
运行上述代码后,您将遇到如下所示的错误消息:
运行代码的错误信息如下:
File "/home/madici/Desktop/helloworld.py", line 1 print("Hello World) ^ SyntaxError: unterminated string literal (detected at line 1)
要解决这些错误,请使用正确的 Python 语法,如下所示:
print("Hello World") age = 20 if age > 18: print("Age is over 18") def square(x): return x * x print(square(4))
缩进错误
与使用大括号分隔代码块的其他语言(如 Java、C 或 C++)不同,Python 使用缩进来定义代码块的层次结构和结构。 例如,在用 Java 编写控制语句时,一旦条件被评估,所有要执行的代码都包含在大括号内。
然而,在 Python 中,代码块将被缩进。 Python 中的典型缩进由四个空格或一个制表符组成。 但是,只要在编写的代码中保持一致,空格的数量并不重要。
作为 Python 程序员,当您未能添加所需的缩进时,您可能会遇到缩进错误,例如在编写控制语句或函数时,当您同时使用制表符和空格来创建缩进时,因为它会混淆解释器,当您放置缩进时在错误的地方或当您的缩进在整个代码库中不一致时。
导致缩进错误的代码示例如下所示:
age = 20 if age > 18: print("Age is greater than 18") print("You're allowed to drive") else: print("Age is less than 18")
上述代码产生的错误消息如下所示:
运行代码的错误信息如下:
File "/home/madici/Desktop/helloworld.py", line 3 print("Age is greater than 18") ^ IndentationError: expected an indented block after 'if' statement on line 2
要更正错误,请在 if 语句之后缩进该行,因为缩进是必需的,并确保它与代码其余部分中的缩进相匹配,如下所示:
age = 20 if age > 18: print("Age is greater than 18") print("You're allowed to drive") else: print("Age is less than 18")
类型错误
在 Python 中,TypeError 是当您尝试使用不兼容的数据类型执行操作时出现的异常。 例如,如果您尝试添加一个字符串和一个整数或将一个字符串数据类型与一个整数连接起来,您将遇到 TypeError。
当您使用具有不正确数据类型的函数或方法时,当您尝试使用非整数索引访问可迭代项(如列表)中的项目时,或者当您尝试迭代不可迭代的对象时,您也可能遇到 TypeErrors。
通常,任何使用不正确数据类型的操作都会导致 TypeError。
可能导致类型错误的操作示例如下所示:
# Type Error resulting from concatenating a string an an integer age = 25 message = "I am " + age + " years old." list1 = [1, "hello", 5, "world", 18, 2021] #Type errors resulting from wrong usage of builtin in methods print(sum(list1)) #TypeError resulting from adding a string and an integer num1 = 10 num2 = "16" print(num1 + num2) #TypeError resulting from using a non integer index list2 = ["hello", "from", "the", "other", "side"] print(list2["1"])
上面显示的代码产生的错误消息如下所示:
代码中的示例 TypeError 消息如下所示:
File "/home/madici/Desktop/helloworld.py", line 3, in <module> message = "I am " + age + " years old." ~~~~~~~~^~~~~ TypeError: can only concatenate str (not "int") to str
要消除错误,请使用正确的数据类型或类型转换,如下所示:
age = 25 message = "I am " + str(age) + " years old." list1 = [1, 5, 18, 2021] print(sum(list1)) num1 = 10 num2 = "16" print(num1 + int(num2)) list2 = ["hello", "from", "the", "other", "side"] print(list2[1])
属性错误
在 Python 中,当您尝试使用对象上不存在的属性或调用对象上不存在的方法时,会发生 AttributeError。 AttributeError 表明对象没有被调用的属性或方法。
例如,如果您对整数调用字符串方法,您将遇到 AttributeError,因为该方法在您调用它的对象类型上不存在。
在下面显示的示例中,用于将字符串的第一个字母转换为大写的 capitalize() 方法在整数上被调用。 结果是属性错误,因为 int 没有 capitalize() 方法。
# AttributeError arising from calling capitalize() on an int value num = 1445 cap = num.capitalize() print(cap)
运行此代码会产生如下所示的错误消息:
代码中的 AttributeError 消息如下:
File "/home/madici/Desktop/helloworld.py", line 3, in <module> cap = num.capitalize() ^^^^^^^^^^^^^^ AttributeError: 'int' object has no attribute 'capitalize'
要解决 AttributeError,请确保您调用的方法或属性存在于您调用它的对象类型上。 在这种情况下,对字符串数据类型调用 capitalize() 可以解决此错误,如下所示:
导入错误
当您尝试导入在当前环境中找不到或无法访问的模块时,Python 中的 ImportError 就会发生。 可能是它尚未安装,您没有正确配置它的路径,或者您拼错了您要安装的模块。
ImportError 有一个名为 ModuleNotFoundError 的子类,这是当您尝试导入无法找到的模块时抛出的错误。
例如,下面的代码尝试导入数据分析库 pandas 时会抛出这样的错误,因为该模块尚未安装。
生成的 ImportError 消息如下所示:
File "/home/madici/Desktop/helloworld.py", line 1, in <module> import pandas ModuleNotFoundError: No module named 'pandas'
要解决此类错误,请确保已安装您尝试导入的模块。 如果这不能解决错误,请检查您是否使用正确的模块拼写和正确的文件路径来访问模块。
值错误
这是当 Python 中的函数接收到正确数据类型的值但该值是不合适的值时发生的异常。 例如,如果您传入负数,用于计算数值平方根的 Math.sqrt() 函数将返回 ValueError。
尽可能多的值是正确的类型,即一个数值,负数使它成为不合适的值
如果您传入的字符串不是数字字符串值,则转换数字或字符串的函数 int() 将返回 ValueError。 将“123”或“45”传递给函数不会返回错误,因为字符串可以转换为适当的整数值。
但是,如果您传入的字符串不是数字字符串值(例如“Hello”),它会返回 ValueError。 这是因为“Hello”虽然是一个字符串,但不合适,因为它没有等效的整数。
生成 ValueError 的代码示例如下所示:
# Value error resulting from inappropriate int value in sqrt() import math num = -64 root = math.sqrt(num) print(root) # Value error resulting from passing a string with no integer # equivalent into int() function numString = "Hello" num = int(numString) print(num)
上面代码的错误如下所示:
生成的错误信息如下:
File "/home/madici/Desktop/helloworld.py", line 4, in <module> root = math.sqrt(num) ^^^^^^^^^^^^^^ ValueError: math domain error
要更正错误,请在函数中使用适当的值,如下所示:
import math num = 64 root = math.sqrt(num) print(root) numString = "5231" num = int(numString) print(num)
IO错误
IOError(Input/Output Error) 是输入或输出操作失败时发生的异常。 这可能是由于尝试访问不存在的文件、设备中的磁盘存储空间不足、尝试访问您没有足够权限访问的文件或当您尝试访问当前正在使用的文件时造成的通过其他操作。
处理文件时通常使用的诸如 open()、read()、write() 和 close() 之类的方法很可能会导致此类错误。
考虑下面的代码,它试图打开一个不存在的名为“notes.txt”的文件。 该代码会导致 IOError,从而引发 FileNotFoundError:
出现以下错误消息:
File "/home/madici/Desktop/helloworld.py", line 2, in <module> file1 = open("notes.txt", "r") ^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'
为避免上述错误,您需要做的就是确保“notes.txt”文件存在于您运行终端的目录中。另一种处理 IOErrors 的方法是使用 try except 块,如下所示:
名称错误
NameError 是当您尝试使用不存在、未在当前范围内定义或未分配值的变量、函数或模块时会遇到的异常。
当您拼错变量或函数名称或在定义它们之前使用它们时,通常会发生此类错误。 在不导入的情况下使用模块也会导致 NameError。
以下代码将导致 NameError 异常:
# name error arises because the math module has not been imported num = 64 root = math.sqrt(64) print(root) # NameError arises because x is used before it is defined y = 23 print(x) #NameEror because function name is not defined def greet(): print("Good morning") great() #ameError: name 'great' is not defined
以下错误消息由上面的代码产生:
示例 NameError 消息如下所示:
File "/home/madici/Desktop/helloworld.py", line 3, in <module> root = math.sqrt(64) ^^^^ NameError: name 'math' is not defined
要解决此类 NameError,请确保在导入模块之前没有使用模块,在定义变量或函数之前没有使用它们,并且没有拼错函数或变量名称:
import math num = 64 root = math.sqrt(64) print(root) y = 23 print(y) def greet(): print("Good morning") greet()
索引错误
IndexError 是当您尝试访问超出范围的列表或元组中的索引时发生的异常。 考虑下面的列表:
list1 = [1, 2, 3, 4, 5]
该列表有五个元素。 Python 从 0(零)开始计算索引。 因此,上面的列表的索引范围从 0 到 n-1,n 是列表中的数字或元素。 在这种情况下,索引或列表的范围为 0 到 4。
如果您尝试访问索引大于 4 的元素,您将遇到 IndexError,因为该索引超出了您尝试从中访问元素的列表中的范围。 下面的代码会生成一个 IndexError:
list1 = [1, 2, 3, 4, 5] item = list1[6] #IndexError because the list index is out of range print(item)
代码中的错误如下所示:
生成的 IndexError 信息如下:
File "/home/madici/Desktop/helloworld.py", line 2, in <module> item = list1[6] #IndexError because the list index is out of range ~~~~~^^^ IndexError: list index out of range
避免 IndexError 的最佳方法是使用 range() 和 len() 函数来确保您只访问范围内的元素,如下所示:
list1 = [1, 2, 3, 4, 5] for i in range(len(list1)): print(list1[i])
按键错误
KeyError 是当您尝试使用键访问字典中的项目但在字典中找不到该键时发生的异常。 考虑下面的字典:
cities = {"Canada": "Ottawa", "USA": "Washington", "Italy": "Rome"}
字典中的键是“加拿大”、“美国”、“意大利”。 您可以使用三个键访问城市字典中的项目。 但是,如果您尝试使用不存在的键访问元素,例如“巴西”,您将遇到 KeyError,如下所示:
生成的 KeyError 信息如下所示:
File "/home/madici/Desktop/helloworld.py", line 6, in <module> print(cities["Brazil"]) ~~~~~~^^^^^^^^^^ KeyError: 'Brazil'
要解决 KeyError,请确保您用于访问字典中元素的键确实存在于字典中。 为此,您可以像这样使用 if…else 语句:
cities = {"Canada": "Ottawa", "USA": "Washington", "Italy": "Rome"} country = "Canada" if country in cities: print("The capital city of " + country + " is " + cities[country]) else: print("The key " + country + " is not present in the cities dictionary")
这样,您就可以避免在访问字典中的元素时遇到 KeyErrors
结论
使用 Python 编码时,无论您的专业水平如何,都一定会遇到错误。 因此,请务必熟悉本文中突出显示的不同类型的错误,以确保您能够在它们出现时进行处理。
您还可以探索一些有用的 Python 单行代码来简化常见任务。