写Python的时候遇到的一些常见的错误

1.语法错误

if 'b' in list1:
    print('存在')
    return
else:
    print('不存在')

SyntaxError: 'return' outside funtion

语法错误:return 在函数外使用

解决方法:将return放在函数中

if 'b' in list1:
    print('存在'
else:
    print('不存在')

SyntaxError:  invalid syntax

语法错误:非法的语法

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

2.类型错误

name = '张三'
fond = 1
print(name + '喜欢' + fond)

TypeError: must be str,not int

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

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

dic1.pop()

TypeError:pop expected at least 1 arguments,got 0

类型错误:pop方法期望得到至少一个参数,但是现在参数为0

3.索引错误

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

IndexError:list index out of range

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

解决方法:查看列表的长度,索引要小于长度

4.缩进错误

if 'b' in list1:
        print('存在')
    else:
    print('不存在')

IndentationError:unindent does not match any outer indentation level

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

if 'b' in list1:
        print('存在')
else:
print('不存在')

IndentationError: expected an indented block

缩进错误:期望一个缩进TAB

5.键错误

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

KeyError: 'fond'

键错误:没有指定的键值

6.值错误

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

ValueError: substring not found

值错误:子字符串未找到

7.属性错误

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

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

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

猜你喜欢

转载自blog.csdn.net/qq_42603652/article/details/80991509
今日推荐