Python開發(fā)中最常見的錯誤大全及解決方法
引言
Python 以“簡潔易讀”著稱,但即便是經(jīng)驗豐富的開發(fā)者,也常被各種錯誤搞得焦頭爛額。這些錯誤不僅影響開發(fā)效率,還可能潛伏在生產環(huán)境中引發(fā)嚴重故障。
本文系統(tǒng)梳理了 Python 中最常見的錯誤類型,并特別深入解析了 JSON 相關錯誤——這是 Web 開發(fā)、API 調用和數(shù)據(jù)處理中最頻繁出現(xiàn)的問題之一。每類錯誤都配有 真實示例 + 原理解釋 + 解決方案,助你快速排錯、寫出健壯代碼。
一、錯誤分類概覽
Python 錯誤主要分為三類:
- 語法錯誤(SyntaxError) :代碼不符合 Python 語法規(guī)則,解釋器直接拒絕運行。
- 運行時異常(Exceptions) :程序能啟動,但在執(zhí)行過程中因邏輯或環(huán)境問題崩潰。
- 邏輯錯誤(Logic Errors) :代碼能運行且不報錯,但結果不符合預期(最難調試)。
我們重點討論前兩類,并加入 JSON 專項章節(jié)。
二、語法錯誤(SyntaxError)
這類錯誤在保存或運行腳本時立即暴露。
常見場景:
- 缺少冒號
:(if,for,def后必須加) - 括號/引號不匹配
- 錯誤縮進(混用空格與 Tab)
# ? 典型錯誤
if x > 0
print("positive") # SyntaxError: invalid syntax
# ? 正確寫法
if x > 0:
print("positive")
建議:使用支持語法高亮和括號匹配的編輯器(如 VS Code、PyCharm)。
三、運行時異常(Exceptions)
1. NameError:變量未定義
print(username) # NameError: name 'username' is not defined
解決:確保變量已賦值,注意作用域。
2. AttributeError:對象無此屬性
[].push(1) # AttributeError: 'list' object has no attribute 'push'
解決:查官方文檔,確認方法名(如 list.append())。
3. IndexError / KeyError:越界訪問
d = {"name": "Alice"}
print(d["age"]) # KeyError: 'age'
安全訪問:
d.get("age", "未知") # 推薦
# 或
if "age" in d: ...
4. TypeError:類型不匹配
"5" + 3 # TypeError: can only concatenate str (not "int") to str
解決:顯式轉換類型,如 int("5") + 3。
5. ValueError:值合法但不符合要求
int("abc") # ValueError: invalid literal for int()
防御性編程:
try:
num = int(user_input)
except ValueError:
print("請輸入有效數(shù)字")
6. ZeroDivisionError:除零錯誤
10 / 0 # ZeroDivisionError
檢查分母:
if denominator != 0:
result = numerator / denominator
7. FileNotFoundError:文件不存在
open("missing.txt") # FileNotFoundError
安全打開:
import os
if os.path.exists("file.txt"):
with open("file.txt") as f: ...
8. ModuleNotFoundError:模塊未安裝
import requests # ModuleNotFoundError(若未安裝)
解決:
pip install requests
四、經(jīng)典邏輯陷阱
可變默認參數(shù)(Mutable Default Argument)
# ? 危險!
def add(item, lst=[]):
lst.append(item)
return lst
print(add(1)) # [1]
print(add(2)) # [1, 2] ← 意外共享!
# ? 正確
def add(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
黃金法則:永遠不要用 list、dict、set 等可變對象作為函數(shù)默認參數(shù)!
五、JSON 專項:最常被忽視的錯誤源
在 API 開發(fā)、配置文件讀取、前后端通信中,JSON 是數(shù)據(jù)交換的通用語言。但處理不當極易出錯。
1.json.JSONDecodeError:JSON 格式非法
這是 最常見 的 JSON 錯誤,通常由以下原因引起:
場景 1:字符串不是合法 JSON
import json
data = "{'name': 'Alice'}" # 注意:用了單引號!
json.loads(data) # JSONDecodeError: Expecting property name enclosed in double quotes
原因:JSON 標準要求 鍵和字符串必須用雙引號 " ,單引號無效。
解決:
- 確保數(shù)據(jù)源輸出標準 JSON(如后端用
json.dumps()) - 若必須解析非標準字符串,可先替換:
data = data.replace("'", '"')
場景 2:末尾多余逗號
data = '{"name": "Alice", "age": 30,}' # 末尾逗號
json.loads(data) # JSONDecodeError
解決:使用在線 JSON 校驗工具(如 jsonlint.com)驗證。
場景 3:響應體為空或 HTML
# 模擬請求返回 404 頁面(HTML) response_text = "<html>Not Found</html>" json.loads(response_text) # JSONDecodeError
防御性處理:
import json
import requests
resp = requests.get("https://api.example.com/data")
try:
data = resp.json() # requests 內部調用 json.loads()
except json.JSONDecodeError:
print("響應不是 JSON!狀態(tài)碼:", resp.status_code)
print("原始內容:", resp.text[:200])
2.TypeError: Object of type xxx is not JSON serializable
當你嘗試把 非 JSON 支持的類型 序列化時發(fā)生:
import json
from datetime import datetime
data = {"time": datetime.now()}
json.dumps(data) # TypeError: Object of type datetime is not JSON serializable
解決方法:
方法 1:自定義default函數(shù)
def json_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
json.dumps(data, default=json_serializer)
方法 2:提前轉換
data = {"time": datetime.now().isoformat()}
json.dumps(data) # OK
方法 3:使用第三方庫(如orjson、ujson)支持更多類型
3. 中文亂碼問題(編碼錯誤)
# 寫入文件
with open("config.json", "w") as f:
json.dump({"消息": "你好"}, f)
# 讀取時可能亂碼(尤其在 Windows)
解決:顯式指定 UTF-8 編碼
# 寫入
with open("config.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False) # 關鍵:ensure_ascii=False
# 讀取
with open("config.json", "r", encoding="utf-8") as f:
data = json.load(f)
兩個關鍵參數(shù):
encoding="utf-8":確保文件以 UTF-8 讀寫ensure_ascii=False:允許輸出中文而非\u4f60\u597d
六、最佳實踐:如何避免和快速定位錯誤?
1. 使用try...except精準捕獲
try:
data = json.loads(api_response)
except json.JSONDecodeError as e:
logger.error(f"JSON 解析失敗: {e.msg} at line {e.lineno}")
except Exception as e:
logger.error(f"未知錯誤: {e}")
2. 啟用類型提示 + mypy
def parse_user(data: str) -> dict:
return json.loads(data) # mypy 可檢查返回類型
3. 單元測試覆蓋異常路徑
def test_invalid_json():
with pytest.raises(json.JSONDecodeError):
parse_user("{'invalid': json}")
4. 日志記錄原始數(shù)據(jù)
當 JSON 解析失敗時,務必記錄原始字符串,便于復現(xiàn)問題。
七、總結
| 錯誤類型 | 高頻場景 | 防御策略 |
|---|---|---|
SyntaxError | 縮進、冒號、括號 | 使用智能 IDE |
NameError | 變量未定義 | 檢查拼寫與作用域 |
JSONDecodeError | 非標準 JSON、空響應 | 校驗 + try-except + 記錄原始數(shù)據(jù) |
TypeError(序列化) | datetime、自定義對象 | 自定義 default 或預轉換 |
| 可變默認參數(shù) | 函數(shù)默認值為 list/dict | 用 None 代替 |
記住:
“錯誤不是敵人,而是你代碼的反饋。”
學會閱讀錯誤信息(尤其是 traceback 和JSONDecodeError的lineno),是成為高效 Python 開發(fā)者的關鍵一步。
以上就是Python開發(fā)中最常見的錯誤大全及解決方法的詳細內容,更多關于Python最常見的錯誤大全的資料請關注腳本之家其它相關文章!
相關文章
python神經(jīng)網(wǎng)絡Densenet模型復現(xiàn)詳解
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡Densenet模型復現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
Python使用sigthief簽發(fā)證書的實現(xiàn)步驟
Windows 系統(tǒng)中的一些非常重要文件通常會被添加數(shù)字簽名,其目的是用來防止被篡改,能確保用戶通過互聯(lián)網(wǎng)下載時能確信此代碼沒有被非法篡改和來源可信,從而保護了代碼的完整性、保護了用戶不會被病毒、惡意代碼和間諜軟件所侵害,本章將演示證書的簽發(fā)與偽造2021-06-06

