Python ——报错集锦

错误(1):SyntaxError:'return' outside function

错误代码:

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

错误分析:语法错误,return放在了方法体外面

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

错误(2TypeError:must be str,not int

错误代码:

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

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

解决办法:在使用+拼接的时候 必须使用字符串 或者将数字转化为字符串

错误(3IndentationError: unindent does not match any outer indentation level

错误代码:

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

错误分析:Indent 是缩进错误:未知缩进不匹配任何缩进等级

解决办法:tab自动缩进

错误(4)SyntaxError: invalid syntax

错误代码:

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

错误分析:语法错误 , 非法的语法

解决办法:报错后 看报错信息在第几行,从这一行往上看

错误(5 IndexError: string index out of range

错误代码:

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

错误分析:索引错误,字符串超出了范围

解决办法:查看字符串的长度 索引要小于长度

错误(6)ValueError: substring not found

错误代码:

content = 'hello world'
result = content.index('a')
print(result)

错误分析:子字符串未找到

解决办法:子字符串必须存在于上方字符串中

错误(7IndexError: list index out of range

错误代码:

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

错误分析:索引错误:列表索引超出范围

解决办法:索引值必须在列表索引范围内

错误(8AttributeError: 'tuple' object has no attribute 'remove'

错误代码:

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

错误分析:Attribute属性 object 对象   属性错误,元组对象没有属性‘remove’

解决办法:不对元组中元素进行‘remove’操作

错误(9)KeyError: 'fond'

错误代码:

dic1 = {
    'name': '张三',
    'age' : 17 ,
    'friend':['李四','王五','赵六','冯七']
}
print(dic1['fond'])
错误分析:Key 键错误,字典里没有指定的键值’fond’

解决办法:要找字典内含有的key或value值

错误(10)TypeError: pop expected at least 1 arguments, got 0

错误代码:

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

错误分析:arguements 参数 expected期望 at least至少类型错误:pop方法希望得到至少一个参数,但是现在参数为0

解决办法:在dic1.pop()中输入dic1中有的非空参数







猜你喜欢

转载自blog.csdn.net/weixin_42660771/article/details/80990665