首页 > 技术文章 > 常见的Python运行时错误

mxxct 2020-10-22 10:36 原文

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()

推荐阅读