17个新手常见Python运行时错误
来源:天融信教育
当初学 Python 时,想要弄懂 Python 的错误信息的含义可能有点复杂。这里列出了常见的的一些让你程序 crash 的运行时错误。
1) 忘记在 if , elif , else , for , while , class , def 声明末尾添加 :(导致 “ SyntaxError :invalid syntax ”)
2) 使用 = 而不是 ==(导致“ SyntaxError: invalid syntax ”)
3) 错误的使用缩进量。(导致“ IndentationError:unexpected indent ”、“ IndentationError:unindent does not match any outer indetation level ”以及“ IndentationError:expected an indented block ”)
4) 在 for 循环语句中忘记调用 len() (导致“ TypeError: ‘list’ object cannot be interpreted as an integer ”)
5) 尝试修改string的值(导致“ TypeError: ‘str’ object does not support item assignment ”)
6) 尝试连接非字符串值与字符串(导致 “ TypeError: Can’t convert ‘int’ object to str implicitly ”)
7) 在字符串首尾忘记加引号(导致“ SyntaxError: EOL while scanning string literal ”)
8) 变量或者函数名拼写错误(导致“ NameError: name ‘fooba’ is not defined ”)
9) 方法名拼写错误(导致 “ AttributeError: ‘str’ object has no attribute ‘lowerr ‘”)
10) 引用超过list最大索引(导致“ IndexError: list index out of range ”)
11) 使用不存在的字典键值(导致“KeyError:‘spam’”)
12) 尝试使用Python关键字作为变量名(导致“ SyntaxError:invalid syntax ”)
13) 在一个定义新变量中使用增值操作符(导致“ NameError: name ‘foobar’ is not defined ”)
14) 在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在)(导致“ UnboundLocalError: local variable ‘foobar’ referenced before assignment ”)
15) 尝试使用 range()创建整数列表(导致“ TypeError: ‘range’ object does not support item assignment ”)
16) 不错在 ++ 或者 — 自增自减操作符。(导致“ SyntaxError: invalid syntax ”)
17) 忘记为方法的第一个参数添加self参数(导致“TypeError: myMethod() takes no arguments (1 given)”)