初學(xué)Python常見異常錯(cuò)誤,總有一處你會(huì)遇到!

初學(xué)Python常見錯(cuò)誤
忘記寫冒號(hào)
誤用=
錯(cuò)誤 縮緊
變量沒有定義
中英文輸入法導(dǎo)致的錯(cuò)誤
不同數(shù)據(jù)類型的拼接
索引位置問題
使用字典中不存在的鍵
忘了括號(hào)
漏傳參數(shù)
缺失依賴庫(kù)
使用了python中對(duì)關(guān)鍵詞
編碼問題
1. 忘記寫冒號(hào)
在 if、elif、else、for、while、def語(yǔ)句后面忘記添加 :
age = 42if age == 42print('Hello!')
File"" , line 2if age == 42^SyntaxError: invalid syntax
2. 誤用?=
= 是賦值操作,而判斷兩個(gè)值是否相等是 ==
gender = '男'if gender = '男':print('Man')
File"" , line 2if gender = '男':^SyntaxError: invalid syntax
3. 錯(cuò)誤的縮進(jìn)
Python用縮進(jìn)區(qū)分代碼塊,常見的錯(cuò)誤用法:
print('Hello!')print('Howdy!')
File"" , line 2print('Howdy!')^IndentationError: unexpected indent
num = 25if num == 25:print('Hello!')
File"" , line 3print('Hello!')^IndentationError: expected an indented block
4. 變量沒有定義
if city in ['New York', 'Bei Jing', 'Tokyo']:print('This is a mega city')
---------------------------------------------------------------------------NameErrorTraceback (most recent call last)22-a81fd2e7a0fd> in ----> 1if city in ['New York', 'Bei Jing', 'Tokyo']:2print('This is a mega city')
NameError: name 'city'isnotdefined
5. 中英文輸入法導(dǎo)致的錯(cuò)誤
英文冒號(hào)
英文括號(hào)
英文逗號(hào)
英文單雙引號(hào)
if5>3:print('5比3大')
File"" , line 1if5>3:^SyntaxError: invalid character in identifier
if5>3:print('5比3大')
File"" , line 2print('5比3大')^SyntaxError: invalid character in identifier
spam = [1, 2,3]
File"" , line 1spam = [1, 2,3]^SyntaxError: invalid character in identifier
if5>3:print('5比3大‘)
File"" , line 2print('5比3大‘)^SyntaxError: EOL while scanning string literal
6. 不同數(shù)據(jù)類型的拼接
字符串/列表/元組 支持拼接
字典/集合不支持拼接
'I have ' + 12 + ' eggs.'#'I have {} eggs.'.format(12)
---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)29-20c7c89a2ec6> in ----> 1'I have ' + 12 + ' eggs.'
TypeError: can only concatenate str (not"int") to str
['a', 'b', 'c']+'def'
---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)31-0e8919333d6b> in ----> 1 ['a', 'b', 'c']+'def'
TypeError: can only concatenate list (not"str") to list
('a', 'b', 'c')+['a', 'b', 'c']
---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)33-90742621216d> in ----> 1 ('a', 'b', 'c')+['a', 'b', 'c']
TypeError: can only concatenate tuple (not"list") to tuple
set(['a', 'b', 'c'])+set(['d', 'e'])
---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)35-ddf5fb1e6c8c> 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 call last)36-1b1456844331> in 2 grades2 = {'David':88, 'Unique':89}3----> 4 grades1+grades2
TypeError: unsupported operand type(s) for +: 'dict'and'dict'
7. 索引位置問題
spam = ['cat', 'dog', 'mouse']print(spam[5])
---------------------------------------------------------------------------IndexErrorTraceback (most recent call last)38-e0a79346266d> in 1 spam = ['cat', 'dog', 'mouse']----> 2print(spam[5])
IndexError: list index out of range
8. 使用字典中不存在的鍵
在字典對(duì)象中訪問 key 可以使用 [],
但是如果該 key 不存在,就會(huì)導(dǎo)致:KeyError: 'zebra'
spam = {'cat': 'Zophie','dog': 'Basil','mouse': 'Whiskers'}print(spam['zebra'])
---------------------------------------------------------------------------KeyErrorTraceback (most recent call last)39-92c9b44ff034> in 3'mouse': 'Whiskers'}4----> 5print(spam['zebra'])
KeyError: 'zebra'
為了避免這種情況,可以使用 get 方法
spam = {'cat': 'Zophie','dog': 'Basil','mouse': 'Whiskers'}print(spam.get('zebra'))
None
key 不存在時(shí),get 默認(rèn)返回 None
9. 忘了括號(hào)
當(dāng)函數(shù)中傳入的是函數(shù)或者方法時(shí),容易漏寫括號(hào)
spam = {'cat': 'Zophie','dog': 'Basil','mouse': 'Whiskers'}print(spam.get('zebra')
File"" , line 5print(spam.get('zebra')^SyntaxError: unexpected EOF while parsing
10. 漏傳參數(shù)
def diyadd(x, y, z):return x+y+zdiyadd(1, 2)
---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)44-7184f3f906ca> in 2return x+y+z3----> 4 diyadd(1, 2)
TypeError: diyadd() missing 1 required positional argument: 'z'
11. 缺失依賴庫(kù)
電腦中沒有相關(guān)的庫(kù)
12. 使用了python中的關(guān)鍵詞
如try、except、def、class、object、None、True、False等
try = 5print(try)
File"" , line 1try = 5^SyntaxError: invalid syntax
def = 6print(6)
File"" , line 1def = 6^SyntaxError: invalid syntax
13. 文件編碼問題
import pandas as pddf = pd.read_csv('data/twitter情感分析數(shù)據(jù)集.csv')df.head()
嘗試encoding編碼參數(shù)傳入utf-8、gbk
df = pd.read_csv('data/twitter情感分析數(shù)據(jù)集.csv', encoding='utf-8')df.head()
都報(bào)錯(cuò)說明編碼不是utf-8和gbk,而是不常見都編碼,這里我們需要傳入正確都encoding,才能讓程序運(yùn)行。
python有個(gè)chardet庫(kù),專門用來偵測(cè)編碼。
import chardetbinary_data = open('data/twitter情感分析數(shù)據(jù)集.csv', 'rb').read()chardet.detect(binary_data)
{'encoding': 'Windows-1252', 'confidence': 0.7291192008535122, 'language': ''}
