Python常见的几种报错类型

 

错误类型1:语法错误

while True :
    count += 1
    if count == 20 :
        return

报错:

SyntaxError: 'return' outside function

语法错误:return不能在方法以外使用

解决方法:将return放在方法体中

 

 

错误类型2:类型错误

name = '小王'
age = 16
print('我的名字是' + name + ',我的年龄是' + age)

报错:

TypeError: must be str, not int

类型错误:必须是一个字符串,不能是数字

解决方法:使用 + 拼接的时候,必须使用字符串,或者将数字转化成字符串

 

错误类型3:语法错误

name = '小王'
if name = '小王':
    print('Hello')

报错:

SyntaxError: invalid syntax

语法错误:非法的语法

解决方法:看报错信息在第几行,从这一行往上找错误

 

 

错误类型4:缩进错误

name = '小王'
for index in range(10):
if name == '小王':
    print('hello')
else:
    print('nothing')

报错:

IndentationError: unindent does not match any outer indentation level

缩进错误 : 未知缩进不匹配任何缩进等级

解决办法:tab自动缩进

 

错误类型5:索引错误

content = 'hello world'
print(content[21])

报错:

 

IndexError: string index out of range
索引错误:字符串超出了范围
解决办法:查看字符串的长度,索引要小于长度

 

错误类型6:值错误

content = 'hello world'
result = content.index('你好')
print(result)

报错:

ValueError: substring not found
值错误:字符串未找到

 

错误类型7:索引错误

list1 = ['outMan','小李子','诺兰','皮克斯']
print(list1[5])

报错:

 

IndexError: list index out of range
索引错误:列表索引超出了范围

 

错误类型8:属性错误

tp1 = ((),[],{},1,2,3,'a','b','c',3.24,True)
tp1.remove(1)

报错:

 AttributeError: 'tuple' object has no attribute 'remove'

 

属性错误:元组对象没有属性'remove'

 

错误类型9:键错误

dic1 = {
    'name':'张三',
    'age':17,
    'friend':['李四','王五','赵六','冯琦']
}
print(dic1['fond'])

报错:

 

KeyError: 'fond'
key键错误:没有指定的键值'fond'

 

错误类型10:类型错误

dic1 = {
    'name':'张三',
    'age':17,
    'friend':['李四','王五','赵六','冯琦']
}
dic1.pop()

报错:

 

TypeError: pop expected at least 1 arguments, got 0
类型错误:pop()方法希望得到至少一个参数,但是现在的参数为0

 

 

 

你可能感兴趣的:(Python常见的几种报错类型)