17个新手常见的Python运行时错误,你都注意到了吗?

17个新手常见的Python运行时错误,你都注意到了吗?

当初学 Python 时,想要弄懂 Python 的错误信息的含义可能有点复杂。这里列出了常见的的一些让你程序 crash 的运行时错误。

1)忘记在 if , elif , else , for , while , class ,def 声明末尾添加 :(导致 “SyntaxError :invalid syntax”)

该错误将发生在类似如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

2)使用 = 而不是 ==(导致“SyntaxError: invalid syntax”)

= 是赋值操作符而 == 是等于比较操作。该错误发生在如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

3)错误的使用缩进量。(导致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”)

记住缩进增加只用在以:结束的语句之后,而之后必须恢复到之前的缩进格式。该错误发生在如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

4)for 循环语句中忘记调用 len() (导致“TypeError: 'list' object cannot be interpreted as an integer”)

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

该错误发生在如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

5)尝试修改string的值(导致“TypeError: 'str' object does not support item assignment”)

string是一种不可变的数据类型,该错误发生在如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

而你实际想要这样做:

17个新手常见的Python运行时错误,你都注意到了吗?

6)尝试连接非字符串值与字符串(导致 “TypeError: Can't convert 'int' object to str implicitly”)

该错误发生在如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

而你实际想要这样做:

17个新手常见的Python运行时错误,你都注意到了吗?

7)在字符串首尾忘记加引号(导致“SyntaxError: EOL while scanning string literal”)

该错误发生在如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

8)变量或者函数名拼写错误(导致“NameError: name 'fooba' is not defined”)

该错误发生在如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

9)方法名拼写错误(导致 “AttributeError: 'str' object has no attribute 'lowerr'”)

该错误发生在如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

10)引用超过list最大索引(导致“IndexError: list index out of range”)

该错误发生在如下代码中:

17个新手常见的Python运行时错误,你都注意到了吗?

今天就分享10个常见的错误啦,剩下的7个明天更新,喜欢的话记得转发+评论哦!

另外关注我有惊喜,惊喜就在置顶文章里面哦!!!