python常见的语法错误和异常
语法错误
指代码不符合Python语法规范,而在程序运行过程中出现的错误称为 异常
异常
的“错误消息”会显示 Traceback (most recent call back)
,而 语法错误
不会显示
一、语法错误
SyntaxError
invalid syntax
SyntaxError: invalid syntax
无效语法
通常有以下几种情况
第一种: 遗漏了标点符号
定义函数括号后面忘了冒号
if条件判断后面忘了冒号
for循环的可迭代对象的后面忘了冒号
while循环后面忘了冒号
字典的键值对之间没有英文逗号
将等于 == 和赋值 = 搞混
第二种: 关键字拼写错误或遗漏
del写成dee
while写成whlie
for..in..的 in 忘了
第三种: 变量名或函数名使用了关键字
1 | # del是关键字,不可用作变量名 |
Python检验关键字见:https://www.gaoyuanqi.cn/python-module-keyword/
invalid character in identifier
SyntaxError: invalid character in identifier
标识符中有无效字符
通常是使用了中文符号
1 | # 使用了中文逗号和引号 |
EOL while scanning string literal
SyntaxError: EOL while scanning string literal
检查到不完整的字符串
通常是遗漏了或混用了两边引号
1 | # 遗漏了右边引号 |
IndentationError
缩进错误
缩进
指四个空格或一个Tab键
expected an indented bloc
IndentationError: expected an indented bloc
需要缩进的代码块
1 | a = ['1314', '520', '雨园'] |
应该缩进的地方
def函数的创建
class类的创建
if条件判断语句
for循环语句
while循环语句
unindent does not match any outer indentation level
IndentationError: unindent does not match any outer indentation level
缩进内容不匹配任何一个层级
1 | a = 4 |
print(a)
要么和if平级,要么和for平级
二、异常
TypeError
类型错误
unsupported operand type(s) for
TypeError: unsupported operand type(s) for +: 'xxx' and 'xxx'
不支持的运算
1 | a = 1314 # 整数 |
can only concatenate str (not “int”) to str
TypeError: can only concatenate str (not "int") to str
只能用字符串拼接字符串
1 | a = '雨园' # 字符串 |
‘xxx’ object is not iterable
TypeError: 'xxx' object is not iterable
xxx对象不可被迭代
1 | # 整数不是可迭代对象 |
可迭代对象
字符串
列表
元组
字典
不是可迭代对象
整数
浮点数
布尔值
None
xxx index out of range
IndexError: xxx index out of range
索引超出了xxx范围
xxx可以是list tuple str dict其中之一
1 | a = [1, 2, 3, 4, 5] |
列表的索引方向有两种:
从左往右: 索引的最小值为 0
,最大值为 列表长度-1
从右往左: 索引的最小值为 -列表长度
,最大值为 -1
求列表长度: len(list)