python常见错误集合

    使用python会出现各种各样的错误,所以在此专门设立了一个博客,在今后使用的过程中,遇到不同的问题都会把它整理到这个博客下面。

1.  忘记在 if , elif , else , for , while , class , def 声明末尾添加符号  :

导致“ SyntaxError :invalid syntax ”(语法错误:无效语法)

该类错误代码如下:

age = 8
if age < 10
    print('年龄太小')

2.  使用 + 拼接时产生的错误

TypeError: must be str, not int(类型错误:必须是一个字符串,不能是数字)

错误代码如下:

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

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

3.  错误的使用缩进量

  导致  IndentationError: unindent does not match any outer indentation level

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

错误代码如下:

if num == 42:
    print('Hello!')
  print('Howdy!')

解决办法:Tab自动缩进

4.  引用超过字符串的最大索引

导致 IndexError: string index out of range(索引错误:超出范围的字符串索引)

错误代码如下:

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

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

5.  引用超过列表的最大索引

导致 IndexError: list index out of range(索引错误:超出范围的列表索引)

错误代码如下:

spam = ['cat', 'dog', 'mouse']
print(spam[6])

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

6.  使用不存在的属性

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

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

错误代码如下:

tp1 = (1,2,3,'a','b','c')
tp1.remove(1)
print(tp1)

7.  使用不存在的字典键

KeyError: 'fond'(key 键错误 没有指定的键值“fond”)

错误代码如下:

dic1 = {'name': '张三','age' : 17}
print(dic1['fond'])

8.  类型错误

TypeError: pop expected at least 1 arguments, got 0

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

错误代码如下:

dic1 = {'name': '张三','age' : 17}
dic1.pop()
print(dic1)

解决办法:pop里面需要写参数 参数为想要删除的key值


持续更新中.............                                                                                              

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值