初学Python常见错误忘记写冒号
误用=
错误 缩紧
变量没有定义
中英文输入法导致的错误
不同数据类型的拼接
索引位置问题
使用字典中不存在的键
忘了括号
漏传参数
缺失依赖库
使用了python中对关键词
编码问题
1. 忘记写冒号
在 if、elif、else、for、while、def语句后面忘记添加:age =42
ifage ==42
print('Hello!')File"", line2
ifage ==42
^
SyntaxError: invalid syntax
2. 误用=
=是赋值操作,而判断两个值是否相等是==gender ='男'
ifgender ='男':
print('Man')File"", line2
ifgender ='男':
^
SyntaxError: invalid syntax
3. 错误的缩进
Python用缩进区分代码块,常见的错误用法:print('Hello!')
print('Howdy!')File"", line2
print('Howdy!')
^
IndentationError: unexpected indentnum =25
ifnum ==25:
print('Hello!')File"", line3
print('Hello!')
^
IndentationError: expected an indented block
4. 变量没有定义ifcityin['New York','Bei Jing','Tokyo']:
print('This is a mega city')---------------------------------------------------------------------------
NameErrorTraceback(most recent calllast)
in
---->1ifcityin['New York','Bei Jing','Tokyo']:
2print('This is a mega city')NameError: name'city'isnotdefined
5. 中英文输入法导致的错误英文冒号
英文括号
英文逗号
英文单双引号if5>3:
print('5比3大')File"", line1
if5>3:
^
SyntaxError: invalid characterinidentifierif5>3:
print('5比3大')File"", line2
print('5比3大')
^
SyntaxError: invalid characterinidentifierspam = [1,2,3]File"", line1
spam = [1,2,3]
^
SyntaxError: invalid characterinidentifierif5>3:
print('5比3大‘)File"", line2
print('5比3大‘)
^
SyntaxError: EOL while scanning string literal
6. 不同数据类型的拼接
字符串/列表/元组 支持拼接
字典/集合不支持拼接'I have '+12+' eggs.'
#'I have {} eggs.'.format(12)---------------------------------------------------------------------------
TypeErrorTraceback(most recent calllast)
in
---->1'I have '+12+' eggs.'TypeError: can only concatenate str (not"int") to str['a','b','c']+'def'---------------------------------------------------------------------------
TypeErrorTraceback(most recent calllast)
in
---->1['a','b','c']+'def'TypeError: can only concatenate list (not"str") to list('a','b','c')+['a','b','c']---------------------------------------------------------------------------
TypeErrorTraceback(most recent calllast)
in
---->1('a','b','c')+['a','b','c']TypeError: can only concatenate tuple (not"list") to tupleset(['a','b','c'])+set(['d','e'])---------------------------------------------------------------------------
TypeErrorTraceback(most recent calllast)
in
---->1set(['a','b','c'])+set(['d','e'])TypeError: unsupported operand type(s)for+:'set'and'set'grades1 = {'Mary':99,'Henry':77}
grades2 = {'David':88,'Unique':89}
grades1+grades2---------------------------------------------------------------------------
TypeErrorTraceback(most recent calllast)
in
2grades2 = {'David':88,'Unique':89}
3
---->4grades1+grades2TypeError: unsupported operand type(s)for+:'dict'and'dict'
7. 索引位置问题spam = ['cat','dog','mouse']
print(spam[5])---------------------------------------------------------------------------
IndexErrorTraceback(most recent calllast)
in
1spam = ['cat','dog','mouse']
---->2print(spam[5])IndexError: list indexoutof range
8. 使用字典中不存在的键
在字典对象中访问 key 可以使用[],
但是如果该 key 不存在,就会导致:KeyError: 'zebra'spam = {'cat':'Zophie',
'dog':'Basil',
'mouse':'Whiskers'}
print(spam['zebra'])---------------------------------------------------------------------------
KeyErrorTraceback(most recent calllast)
in
3'mouse':'Whiskers'}
4
---->5print(spam['zebra'])KeyError:'zebra'
为了避免这种情况,可以使用 get 方法spam = {'cat':'Zophie',
'dog':'Basil',
'mouse':'Whiskers'}
print(spam.get('zebra'))None
key 不存在时,get 默认返回 None
9. 忘了括号
当函数中传入的是函数或者方法时,容易漏写括号spam = {'cat':'Zophie',
'dog':'Basil',
'mouse':'Whiskers'}
print(spam.get('zebra')File"", line5
print(spam.get('zebra')
^
SyntaxError: unexpected EOFwhileparsing
10. 漏传参数defdiyadd(x, y, z):
returnx+y+z
diyadd(1,2)---------------------------------------------------------------------------
TypeErrorTraceback(most recent calllast)
in
2returnx+y+z
3
---->4diyadd(1,2)TypeError: diyadd() missing1required positional argument:'z'
11. 缺失依赖库
电脑中没有相关的库
12. 使用了python中的关键词
如try、except、def、class、object、None、True、False等try=5
print(try)File"", line1
try=5
^
SyntaxError: invalid syntaxdef=6
print(6)File"", line1
def=6
^
SyntaxError: invalid syntax
13. 文件编码问题importpandasaspd
df = pd.read_csv('data/twitter情感分析数据集.csv')
df.head()
尝试encoding编码参数传入utf-8、gbkdf = pd.read_csv('data/twitter情感分析数据集.csv', encoding='utf-8')
df.head()
都报错说明编码不是utf-8和gbk,而是不常见都编码,这里我们需要传入正确都encoding,才能让程序运行。
python有个chardet库,专门用来侦测编码。importchardet
binary_data = open('data/twitter情感分析数据集.csv','rb').read()
chardet.detect(binary_data){'encoding':'Windows-1252','confidence':0.7291192008535122,'language':''}