1. NameError:name 'xxx' is not defined
NameError:name 'xxx' is not defined 是Python中最常见的报错之一,它表示程序中使用的变量名未定义,即没有被赋值。解决的方法是检查程序是否正确定义了该变量,如果没有,则需要使用正确的变量名来定义变量,例如:
# 正确的变量定义 name = 'John' # 错误的变量定义 name_ = 'John'
2. SyntaxError: invalid syntax
SyntaxError: invalid syntax 是由于程序中出现了语法错误而导致的报错,例如:
# 错误的语法 print "Hello world
解决的方法是检查程序中是否出现了语法错误,如果有,则需要更正,例如:
# 正确的语法 print("Hello world")
3. TypeError: 'xxx' object is not iterable
TypeError: 'xxx' object is not iterable 是由于在程序中尝试对一个不可迭代的对象进行迭代操作而导致的报错,例如:
# 错误的操作 for i in 1: print(i)
解决的方法是检查程序中是否尝试对一个不可迭代的对象进行迭代操作,如果有,则需要更正,例如:
# 正确的操作 list = [1, 2, 3] for i in list: print(i)
4. IndexError: list index out of range
IndexError: list index out of range 是由于在程序中尝试访问列表中不存在的索引而导致的报错,例如:
# 错误的操作 list = [1, 2, 3] print(list[3])
解决的方法是检查程序中是否尝试访问列表中不存在的索引,如果有,则需要更正,例如:
# 正确的操作 list = [1, 2, 3] print(list[2])
5. KeyError: 'xxx'
KeyError: 'xxx' 是由于在程序中尝试访问字典中不存在的键而导致的报错,例如:
# 错误的操作 dict = {'name': 'John'} print(dict['age'])
解决的方法是检查程序中是否尝试访问字典中不存在的键,如果有,则需要更正,例如:
# 正确的操作 dict = {'name': 'John'} print(dict['name'])
6. AttributeError: 'xxx' object has no attribute 'xxx'
AttributeError: 'xxx' object has no attribute 'xxx' 是由于在程序中尝试访问对象中不存在的属性而导致的报错,例如:
# 错误的操作 class Person: def __init__(self, name): self.name = name person = Person('John') print(person.age)
解决的方法是检查程序中是否尝试访问对象中不存在的属性,如果有,则需要更正,例如:
# 正确的操作 class Person: def __init__(self, name): self.name = name person = Person('John') print(person.name)