最容易犯的9种异常错误,你有没有中招过

  • 有一些是语法上的错误,比如代码不符合解释器或者编译器的语法

  • 有一些是参数输入错误,比如应该输入整数,结果却输入一个字符串

  • 有一些是逻辑上的漏洞,比如不合法的输入或者算法上计算有些问题

  • 有一些是程序运行错误,比如你要读入文件,而传进来的文件名不存在


1变量或者函数名拼写错误:NameError

访问一个不存在的变量,比如你打印一个从来没有定义过的变量或者你把函数名写错了

language='Python'

print('Welcome to study:'+Language)

>>NameError: name 'Language' is not defined


price = ruond(4.2)

print price

>>NameError: name 'ruond' is not defined


2方法名拼写错误:AttributeError

访问一些未知的对象属性,比如字符串里面一些内置函数名我们拼错

line='Python is easy'

print line.upperr()

>>AttributeError: 'str' object has no attribute 'upperr'


3列表越界:IndexError

比如我们访问list的时候,索引超过了列表的最大索引

names=['XiaoMing','Lao Wang','Zhang li']

print names[3]

>>IndexError: list index out of range


4忘记在if/for/while/def 声明末尾添加 :SyntaxError

有的时候写程序写着写着会忘记if/elif/else/for/while/def的末尾加冒号

score=95

if score >90

print 'very good'

>>SyntaxError: invalid syntax



5在循环语句中忘记调用len():TypeError

有时想通过索引来迭代一个list内元素,for循环中我们经常使用range()函数,但是要记得加入len()而不是直接返回这个列表

companies=['Google','Apple','Facebook']

for i in range(companies):

print i

>>TypeError: range() integer end argument expected, got list.


range()函数要用len()取列表的长度

for i in range(len(companies)):

        print i


6尝试连接非字符串值与字符串:TypeError

有时想把字符串和数值连接起来一起输入,但是会有问题:

score=82

print 'Jack score is: '+str(score)

>>TypeError: cannot concatenate 'str' and 'int' objects


数字必须要转化变成字符串才能连接:

score=82

print 'Jack score is: '+str(score)

>>Jack score is: 82


7访问一未初始化的本地变量:UnboundLocalError

在变量使用的时候特别是在函数内部和外部用相同的变量名,经常会犯错不信你看:

x = 10

def func():

    print x

    x = 1

    

func()

print 'Value of x is', x

>>UnboundLocalError: local variable 'x' referenced before assignment


注意在函数func()中x是局部变量,因为在函数内部又对x进行了赋值为1,这样全局的x和func()中x就不是一个变量,要么改个名字或者x=1删掉,要么就用加上global,表示func()中的x是用的全局的x

x = 10

def func():

global x

print x

x=1


func()

print 'Value of x is', x

>>Value of x is 1


8打开一个不存在的文件:IOError

有的时候我们会访问一个文件,或者定义函数去传入一个文件名,然后去读取

很可能这个文件名根本不存在:

f=open('price.txt')

>>IOError: [Errno 2] No such file or directory: 'price.txt'


9除数为0:ZeroDivisionError

我们在运算一些数值的时候,可能会去引入除数是0的情况,

比如传入一个列表,有可能这个列表中含有0,那么在除的时候就会出错

nums=[10,20,0,30]

for n in nums:

print 100/n

>>ZeroDivisionError: division by zero

猜你喜欢

转载自blog.csdn.net/Two_Brother/article/details/80828765
今日推荐