新四季網

python 遇到錯誤處理(Python常見異常錯誤)

2023-04-16 20:17:28

python 遇到錯誤處理?1. 忘記寫冒號在 if、elif、else、for、while、def語句後面忘記添加 :age = 42if age == 42 print('Hello!'),接下來我們就來聊聊關於python 遇到錯誤處理?以下內容大家不妨參考一二希望能幫到您!

python 遇到錯誤處理

1. 忘記寫冒號

在 if、elif、else、for、while、def語句後面忘記添加 :age = 42if age == 42 print('Hello!')

age = 42 if age == 42 print ( 'Hello!' ) File "" , line 2 if age == 42 ^ SyntaxError : invalid syntax

2. 誤用 =

= 是賦值操作,而判斷兩個值是否相等是 ==

gender = '男' if gender = '男' : print ( 'Man' ) File "" , line 2 if gender = '男' : ^ SyntaxError : invalid syntax

3. 錯誤的縮進

Python用縮進區分代碼塊,常見的錯誤用法:

print('Hello!') print('Howdy!') File "", line 2 print('Howdy!') ^ IndentationError: unexpected indent num = 25 if num == 25: print('Hello!') File "", line 3 print('Hello!') ^ IndentationError: expected an indented block

4. 變量沒有定義

if city in ['New York', 'Bei Jing', 'Tokyo']: print('This is a mega city') --------------------------------------------------------------------------- NameError Traceback (most recent call last) in ----> 1 if city in ['New York', 'Bei Jing', 'Tokyo']: 2 print('This is a mega city') NameError: name 'city' is not defined

5. 中英文輸入法導致的錯誤

英文冒號英文括號英文逗號英文單雙引號

if 5>3: print('5比3大') File "", line 1 if 5>3: ^ SyntaxError: invalid character in identifier if 5>3: print('5比3大') File "", line 2 print('5比3大') ^ SyntaxError: invalid character in identifier spam = [1, 2,3] File "", line 1 spam = [1, 2,3] ^ SyntaxError: invalid character in identifier if 5>3: print('5比3大『) File "", line 2 print('5比3大『) ^ SyntaxError: EOL while scanning string literal

6. 不同數據類型的拼接

字符串/列表/元組 支持拼接

字典/集合不支持拼接

'I have ' 12 ' eggs. '#'I have {} eggs.'.format(12) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in ----> 1 'I have ' 12 ' eggs.' TypeError: can only concatenate str (not "int") to str ['a', 'b', 'c'] 'def' --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in ----> 1 ['a', 'b', 'c'] 'def' TypeError: can only concatenate list (not "str") to list ('a', 'b', 'c') ['a', 'b', 'c'] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in ----> 1 ('a', 'b', 'c') ['a', 'b', 'c'] TypeError: can only concatenate tuple (not "list") to tuple set(['a', 'b', 'c']) set(['d', 'e']) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in ----> 1 set(['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 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) 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]) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) in 1 spam = ['cat', 'dog', 'mouse']----> 2 print(spam[5]) IndexError: list index out of range

8. 使用字典中不存在的鍵

在字典對象中訪問 key 可以使用 [],

但是如果該 key 不存在,就會導致:KeyError: 'zebra'

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'} print(spam['zebra']) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) in 3 'mouse': 'Whiskers'} 4 ----> 5 print(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 "", line 5 print(spam.get('zebra') ^ SyntaxError: unexpected EOF while parsing

10. 漏傳參數

def diyadd(x, y, z): return x y zdiyadd(1, 2) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in 2 return x y z 3 ----> 4 diyadd(1, 2) TypeError: diyadd missing 1 required positional argument: 'z'

11. 缺失依賴庫

電腦中沒有相關的庫

12. 使用了python中的關鍵詞

如try、except、def、class、object、None、True、False等

try = 5print(try) File " ", line 1 try = 5 ^ SyntaxError: invalid syntax def = 6 print(6) File "", line 1 def = 6 ^ SyntaxError: invalid syntax

13. 文件編碼問題

import pandas as pd df = pd.read_csv('data/twitter情感分析數據集.csv') df.head

嘗試encoding編碼參數傳入utf-8、gbk

df = pd.read_csv('data/twitter情感分析數據集.csv', encoding='utf-8') df.head

都報錯說明編碼不是utf-8和gbk,而是不常見都編碼,這裡我們需要傳入正確都encoding,才能讓程序運行。

python有個chardet庫,專門用來偵測編碼。

import chardet binary_data = open('data/twitter情感分析數據集.csv', 'rb').read chardet.detect(binary_data) {'encoding': 'Windows-1252', 'confidence': 0.7291192008535122, 'language': ''}

,
同类文章
葬禮的夢想

葬禮的夢想

夢見葬禮,我得到了這個夢想,五個要素的五個要素,水火只好,主要名字在外面,職業生涯良好,一切都應該對待他人治療誠意,由於小,吉利的冬天夢想,秋天的夢是不吉利的
找到手機是什麼意思?

找到手機是什麼意思?

找到手機是什麼意思?五次選舉的五個要素是兩名士兵的跡象。與他溝通很好。這是非常財富,它擅長運作,職業是仙人的標誌。單身男人有這個夢想,主要生活可以有人幫忙
我不怎麼想?

我不怎麼想?

我做了什麼意味著看到米飯烹飪?我得到了這個夢想,五線的主要土壤,但是Tu Ke水是錢的跡象,職業生涯更加真誠。他真誠地誠實。這是豐富的,這是夏瑞的巨星
夢想你的意思是什麼?

夢想你的意思是什麼?

你是什​​麼意思夢想的夢想?夢想,主要木材的五個要素,水的跡象,主營業務,主營業務,案子應該抓住魅力,不能疏忽,春天夢想的吉利夢想夏天的夢想不幸。詢問學者夢想
拯救夢想

拯救夢想

拯救夢想什麼意思?你夢想著拯救人嗎?拯救人們的夢想有一個現實,也有夢想的主觀想像力,請參閱週宮官方網站拯救人民夢想的詳細解釋。夢想著敵人被拯救出來
2022愛方向和生日是在[質量個性]中

2022愛方向和生日是在[質量個性]中

[救生員]有人說,在出生88天之前,胎兒已經知道哪天的出生,如何有優質的個性,將走在什麼樣的愛情之旅,將與生活生活有什么生活。今天
夢想切割剪裁

夢想切割剪裁

夢想切割剪裁什麼意思?你夢想切你的手是好的嗎?夢想切割手工切割手有一個真正的影響和反應,也有夢想的主觀想像力。請參閱官方網站夢想的細節,以削減手
夢想著親人死了

夢想著親人死了

夢想著親人死了什麼意思?你夢想夢想你的親人死嗎?夢想有一個現實的影響和反應,還有夢想的主觀想像力,請參閱夢想世界夢想死亡的親屬的詳細解釋
夢想搶劫

夢想搶劫

夢想搶劫什麼意思?你夢想搶劫嗎?夢想著搶劫有一個現實的影響和反應,也有夢想的主觀想像力,請參閱週恭吉夢官方網站的詳細解釋。夢想搶劫
夢想缺乏缺乏紊亂

夢想缺乏缺乏紊亂

夢想缺乏缺乏紊亂什麼意思?你夢想缺乏異常藥物嗎?夢想缺乏現實世界的影響和現實,還有夢想的主觀想像,請看官方網站的夢想組織缺乏異常藥物。我覺得有些東西缺失了