date: 2020-04-01 14:25:00

updated: 2020-04-01 14:25:00

常见的Python运行时错误

摘自 菜鸟学Python 公众号

1. SyntaxError:invalid syntax

  1. 忘记在 if,for,def,elif,else,class 等声明末尾加冒号 :
  2. 使用= 而不是 ==

    = 是赋值操作符而 == 是等于比较操作

  3. 尝试使用Python关键字作为变量名
  4. 不存在 ++ 或者 -- 自增自减操作符

2. IndentationError:unexpected indent 或 IndentationError:unindent does not match any outer indetation level 或 IndentationError:expected an indented block

  1. 错误的使用缩进量

    记住缩进增加只用在以结束的语句之后,而之后必须恢复到之前的缩进格式。

3. TypeError: 'list' object cannot be interpreted as an integer

  1. 在 for 循环语句中忘记调用 len()

    通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表。

4. TypeError: 'str' object does not support item assignment

  1. 尝试修改 string 的值,而 string 是一种不可变的数据类型
错误:
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam) 正确:
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)

5. TypeError: Can't convert 'int' object to str implicitly

  1. 尝试连接非字符串值与字符串,需通过 str(int) 来转化

6. SyntaxError: EOL while scanning string literal

  1. 在字符串首尾忘记加引号

7. NameError: name 'fooba' is not defined

  1. 变量或者函数名拼写错误
  2. 使用变量之前为声明改变量

    spam += 1等于spam = spam + 1,意味着 spam 需要有一个初始值

8. AttributeError: 'str' object has no attribute 'lowerr'

  1. 方法名拼写错误

9. IndexError: list index out of range

  1. 引用超过list最大索引

10. KeyError:'id'

  1. 使用不存在的字典键值

    在尝试获取字典键值的时候,先判断是否存在该键

    id = data["id"] if "id" in data.keys() else ""

11. UnboundLocalError: local variable 'foobar' referenced before assignment

  1. 在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)

12. TypeError: 'range' object does not support item assignment

  1. 尝试使用 range()创建整数列表

range() 返回的是 “range object”,而不是实际的 list 值

错误:
spam = range(10)
spam[4] = -1 正确:
spam = list(range(10))
spam[4] = -1

13. TypeError: myMethod() takes no arguments (1 given)

  1. 忘记为方法的第一个参数添加self参数
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()

最新文章

  1. 解决“Dynamic Web Module 3.0 requires Java 1.6 or newer.”错误
  2. Keepalived的安装
  3. express请求及对应的获取说明
  4. 使用maven 如何生成源代码的jar包
  5. Unity使用反射探头实现地面的镜面反射
  6. jenkins2 pipeline插件的10个最佳实践
  7. struts 2.5.5 通配符问题
  8. hdu 2112 (最短路+map)
  9. jquery的ajax同步和异步的理解及示例
  10. 【转】linux之fsck命令
  11. 【CSS】Intermediate4:Background Images
  12. MFC利用ADO建立access数据源 ---包括访问带access密码与不带access密码两种方式)
  13. orientationchange
  14. Windows无法安装到这个磁盘
  15. 使用Atlas进行元数据管理之Type(类型)
  16. 在vultr安装和使用golang
  17. Asp.Net4.5 mvc4(二) 页面创建与讲解
  18. SQLdeveloper同时显示多个表的窗口
  19. Spring Boot log4j多环境日志级别的控制
  20. 10.N个整数中查找是否相加为K[深度搜索]

热门文章

  1. 使用jpa的注意事项
  2. 刷题[FBCTF2019]Event
  3. DVWA SQL-injection 附python脚本
  4. 渗透测试方法论(qf总结)
  5. Java集合-07Map接口及其抽象类
  6. Code Test(1)
  7. 在IDEA创建类时自动创建作者日期等信息设定
  8. >>8) & 0xFF中的 >> 和 &0xFF 的作用
  9. 9.13 考试 T2 区间
  10. Morris遍历