我是靠谱客的博主 害怕野狼,最近开发中收集的这篇文章主要介绍python运行错误-常见的Python运行时错误,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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

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

常见的Python运行时错误

1. SyntaxError:invalid syntax

忘记在 if,for,def,elif,else,class 等声明末尾加冒号 :

使用= 而不是 ==

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

尝试使用Python关键字作为变量名

不存在 ++ 或者 -- 自增自减操作符

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

错误的使用缩进量

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

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

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

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

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

尝试修改 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

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

6. SyntaxError: EOL while scanning string literal

在字符串首尾忘记加引号

7. NameError: name 'fooba' is not defined

变量或者函数名拼写错误

使用变量之前为声明改变量

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

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

方法名拼写错误

9. IndexError: list index out of range

引用超过list最大索引

10. KeyError:'id'

使用不存在的字典键值

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

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

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

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

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

尝试使用 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)

忘记为方法的第一个参数添加self参数

class Foo():

def myMethod():

print('Hello!')

a = Foo()

a.myMethod()

最后

以上就是害怕野狼为你收集整理的python运行错误-常见的Python运行时错误的全部内容,希望文章能够帮你解决python运行错误-常见的Python运行时错误所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部