python新手常见错误和异常
python新手常见的错误和异常
在python编程中,新手最常见的错入和异常如下
1.缺少冒号引起的错误
在if,elif,for,while,class,def声明末尾需要添加冒号(:),如果忘记添加,将会提示:“SyntaxError: invalid syntax”语法错误。例如:
1 |
|
2.将赋值运算符(=)和比较运算符(==)混淆
如果误将=号用作==号,将会提示“SyntaxError: invalid syntax”语法错误,列如:
1 |
|
3.代码结构缩进错误
这是比较常见的错误。当代码结构的缩进不正确时,常常会提示错误信息如:IndentationError: expected an indented block 例如:
1 |
|
4.修改元组和字符串的值报错
元组和字符串的值是不能修改的,如果修改他们的元素值将会提示错误信息。例如:
1 |
|
5.连接字符串和非字符串
如果将字符串和非字符串连接,将会提示错误“TypeError: can only concatenate str (not “int”) to str”
1 |
|
6.在字符串首尾忘记加引号
字符串的首尾必须添加引号,如果没有添加,或者没有成对出现,则会提示错误“SyntaxError: EOL while scanning string literal”例如:
1 |
|
7.变量或者函数名拼写错误
如果函数和变量拼写错误,则会提示错误“NameError: name ‘ab’ is not defined”
1 |
|
8. 应用超过列表的最大索引值
如果引用超过列表的最大索引值,则会提示“IndexError: list index out of range”
1 |
|
9.使用关键字作为变量名
Python 关键字不能用作变量名。Python3 的关键字有:[‘False’, ‘None’, ‘True’, ‘and’, ‘as’,
‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’,’for’, ‘from’, ‘global’, ‘if’, ‘import’,’in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’,’while’, ‘with’, ‘yield’]当使用这些关键字作为变量时,将会提示错误“SyntaxError: invalid syntax”例如:
1
2
3
4
5 >>> except = [12,13,13]
File "<stdin>", line 1
except = [12,13,13]
^
SyntaxError: invalid syntax
10.变量没有初始值就使用增值操作符
如果变量没有指定一个有效的初始值就使用自增操作符,则会提示错误“NameError: name ‘obj’ is not defined”例如:
1
2
3
4 >>> obj += 15
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'obj' is not defined
11.误用自增和自减运算符
在python编程语言中,没有自增(++)或者自减(–)运算符。如果误用,则会提示错误“SyntaxError: invalid syntax”例如:
1
2
3
4
5
6 >>> jj = 10
>>> jj ++
File "<stdin>", line 1
jj ++
^
SyntaxError: invalid syntax
12.忘记为方法的第一个参数添加self参数
在定义方法时,第一个参数必须是self。如果忘记添加self参数,则会提示错误“TypeError: myMethod() takes 0 positional arguments but 1 was given”例如:
1
2
3
4
5
6
7
8
9 >>> class myClass():
... def myMethod():
... print("this is a good method")
...
>>> dd = myClass()
>>> dd.myMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: myMethod() takes 0 positional arguments but 1 was given
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!