Python每天一分钟:python编程中常见的错误一览与修复方法
接触过编程的读者一定对程序运行中出现的错误再熟悉不过了,这些错误有的是因为开发人员疏忽引入的语法错误,有的是缺乏必要检验引起的逻辑或者数据错误,还有的是程序运行中与平台规则冲突引发的系统错误等等。
python中的编程错误
这些错误不可避免地对软件的质量有着非常严重的影响,所以在开发软件的过程中,我们要尽可能的避免这些错误。本文将对python中常见的编程错误予以总结,并介绍修复方法!
python编程常见错误一览
一、语法错误——关键词:SyntaxError
假如我们在python3.x中运行如下代码,会提示什么错误呢?:
print "python"
由于python3中print的使用必须含括号,因此上述代码运行python会报如下错误:
SyntaxError: Missing parentheses in call to 'print'
82 年 18 月 71号考试075分 去掉文字加我的裙
这就是常见的语法错误,关键词:SyntaxError
二、除数为0——ZeroDivisionError
如果出现除数为0的算式,那么python会报如下错误:
>>> a=0 >>> b=1 >>> p = b/a Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> p = b/a ZeroDivisionError: division by zero
三、访问对象属性不存在——AttributeError
如果在python中我们调用某个对象不具有的属性就会出现AttributeError,如下:
>>> testlist = ['python'] >>> testlist .len Traceback (most recent call last): File "<pyshell#9>", line 1, in <module>testlist .len AttributeError: 'list' object has no attribute 'len'
四、索引超出范围——IndexError
索引超出范围很容易理解,就是说序列如果只有1个元素,而代码中却要访问第2个以上的元素,那么就会出现IndexError:
>>> testlist = ['python'] >>> print(testlist[5]) Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> testlist [5] IndexError: list index out of range
五、操作不同数据类型引发错误——TypeError
如果在python中将不同数据类型的变量进行运算就可能出现该错误,比如将字符串类型变量与int类型数字相加:
>>> 6+'python' Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> 6+'python' TypeError: unsupported operand type(s) for +: 'int' and 'str'
六、字典中元素不存在——KeyError
这与序列索引超出范围类似,当访问的元素不在字典中时就会报KeyError:
>>> testdict={'python':666} >>> testdict["python3"] Traceback (most recent call last): File "<pyshell#11>", line 1, in <module>testdict["python3"] KeyError: 'python3'
七、访问不存在的变量——NameError
如果变量没有定义,那么使用该变量就会引发NameError:
>>> print(x) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> x NameError: name 'x is not defined
八、assert条件不成立——AssertionError
>>> testlist = ['python'] >>> assert len(testlist) > 10 Traceback (most recent call last): File "<pyshell#8>", line 1, in <module>assert len(testlist) > 10 AssertionError
一张长图总结
常见python八大错误
避免错误的方式
当代码运行发生错误或者异常时,表示该程序的运行已经出现了问题,导致无法执行后续功能或者直接崩溃。
所以在这种情况下,程序默认是需要停止并退出的,那么倘若我们想让程序在出错影响小的地方不要因为错误而异常退出怎么办呢?处理方式就是大家熟知的:异常捕获与处理!
try...except...
举例如下:
try: 可能产生异常的代码块 except [(Error1, Error2, ...) [as e]]: 处理异常的代码块1 except [(Error3, Error4, ...) [as e]]: 处理异常的代码块2
感兴趣的读者可以自行按照上述格式设计测试代码!
总结
本文只是总结了python中常见的八大编程错误,python中的异常远远不止这些,需要读者多多练习,多多积累!
python的基础学习还是非常简单的,感兴趣的读者可以使用手机上的python小程序来利用零散时间学习python,坚持就有收获!