土薯工具 Toolshu.com 登錄 用戶注冊

Python 新手最常犯的 10 個錯誤:報錯原因與修復方法

原創 作者:bhnw 於 2026-04-09 13:11 發佈 3次瀏覽 收藏 (0)

報錯了,但不知道哪裏錯了

剛開始學 Python,最崩潰的不是寫不出代碼,而是代碼寫出來了,運行一下,紅色報錯刷滿屏幕,完全看不懂。

其實 Python 的錯誤信息非常直接,大多數報錯都有規律可循。這篇文章把新手最常遇到的 10 類錯誤逐一拆解,每種給出報錯原因和修復方法,以後看到紅色不再慌。


1. IndentationError:縮進錯誤

報錯示例:

IndentationError: expected an indented block
IndentationError: unexpected indent

原因: Python 用縮進來表示代碼塊,不是用花括號。縮進不一致,或者該縮進的地方沒縮進,就會報這個錯。

# 錯誤:if 後面的代碼塊沒有縮進
if True:
print("hello")   # ← 這行必須縮進

# 錯誤:混用 Tab 和空格
if True:
    print("hello")  # 4個空格
    print("world")  # 1個Tab(看起來一樣,實際不同)

修復: 統一用4個空格縮進,絕對不要混用 Tab 和空格。在編輯器裏開啓"顯示空白字符"可以直接看出問題。


2. NameError:變量未定義

報錯示例:

NameError: name 'x' is not defined

原因: 使用了一個從未賦值的變量,或者變量名拼寫錯誤。

# 錯誤1:先用後定義
print(name)
name = "Alice"

# 錯誤2:拼寫錯誤
username = "Alice"
print(usrname)   # ← 少了個e

修復: 確保變量在使用前已經賦值,仔細檢查拼寫。Python 區分大小寫,Namename 是兩個不同的變量。


3. TypeError:類型錯誤

報錯示例:

TypeError: can only concatenate str (not "int") to str
TypeError: unsupported operand type(s) for +: 'int' and 'str'

原因: 對不兼容的類型做了操作,最常見的是字符串和數字混用。

# 錯誤:字符串 + 數字
age = 18
print("我今年" + age + "歲")   # ← age 是 int,不能直接拼接

# 錯誤:對字符串做數學運算
score = "90"
print(score + 10)   # ← score 是字符串

修復:str() 把數字轉成字符串,或者用 f-string:

age = 18
print(f"我今年{age}歲")          # f-string,推薦
print("我今年" + str(age) + "歲") # 顯式轉換

score = "90"
print(int(score) + 10)   # 把字符串轉成數字

4. IndexError:索引越界

報錯示例:

IndexError: list index out of range

原因: 訪問了列表中不存在的位置。Python 列表索引從 0 開始,長度爲 n 的列表,有效索引是 0 到 n-1。

fruits = ["apple", "banana", "cherry"]
print(fruits[3])   # ← 只有 0、1、2,沒有 3
print(fruits[-4])  # ← 負索引從-1開始,-4超出範圍

修復:

fruits = ["apple", "banana", "cherry"]
print(len(fruits))      # 先看看長度是多少:3
print(fruits[2])        # 最後一個元素
print(fruits[-1])       # 也是最後一個,推薦寫法

5. KeyError:字典鍵不存在

報錯示例:

KeyError: 'email'

原因: 訪問了字典中不存在的鍵。

user = {"name": "Alice", "age": 28}
print(user["email"])   # ← 字典裏沒有 email 這個鍵

修復方案一:get() 方法,鍵不存在時返回默認值而不是報錯:

print(user.get("email"))           # 返回 None
print(user.get("email", "未填寫")) # 返回默認值"未填寫"

修復方案二: 先判斷鍵是否存在:

if "email" in user:
    print(user["email"])

6. AttributeError:屬性或方法不存在

報錯示例:

AttributeError: 'str' object has no attribute 'append'
AttributeError: 'NoneType' object has no attribute 'split'

原因: 對某個對象調用了它沒有的方法,最常見的兩種情況:把不同類型的方法混用,或者對 None 調用方法。

# 錯誤1:字符串沒有 append 方法(那是列表的)
name = "Alice"
name.append("!")   # ← str 沒有 append

# 錯誤2:函數返回了 None,卻繼續調用方法
result = print("hello")   # print 返回 None
result.upper()             # ← None 沒有 upper 方法

修復: 搞清楚變量的實際類型再調用方法。遇到 NoneType 報錯,先檢查賦值來源是否真的返回了想要的值。


7. ValueError:值不合法

報錯示例:

ValueError: invalid literal for int() with base 10: 'abc'
ValueError: not enough values to unpack

原因: 函數收到了類型正確但值不合法的參數。

# 錯誤1:把不能轉換的字符串轉成整數
num = int("abc")    # ← "abc" 不是數字

# 錯誤2:解包數量不匹配
a, b, c = [1, 2]   # ← 左邊3個變量,右邊只有2個值

修復:

# 轉換前先驗證
s = "abc"
if s.isdigit():
    num = int(s)
else:
    print("不是數字")

# 解包時數量要匹配
a, b = [1, 2]       # 正確
a, *rest = [1, 2, 3, 4]  # 用 * 收集多餘的值

8. ZeroDivisionError:除以零

報錯示例:

ZeroDivisionError: division by zero

原因: 除法的分母是零。聽起來簡單,但實際項目裏分母往往來自用戶輸入或計算結果,很難提前預判。

# 錯誤
total = 0
average = 100 / total   # ← 分母是零

修復: 在除法前判斷分母是否爲零:

total = 0
if total != 0:
    average = 100 / total
else:
    average = 0   # 或者其他默認處理

9. FileNotFoundError:文件不存在

報錯示例:

FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'

原因: 要打開的文件路徑不正確,或者文件根本不存在。

with open("data.txt", "r") as f:   # ← 當前目錄下沒有 data.txt
    content = f.read()

修復:

import os

# 檢查文件是否存在
if os.path.exists("data.txt"):
    with open("data.txt", "r") as f:
        content = f.read()
else:
    print("文件不存在")

# 或者用異常捕獲
try:
    with open("data.txt", "r") as f:
        content = f.read()
except FileNotFoundError:
    print("找不到文件,請檢查路徑")

路徑問題提示:Python 的當前工作目錄不一定是腳本所在目錄,用 os.getcwd() 打印當前目錄確認。


10. RecursionError:遞歸深度超限

報錯示例:

RecursionError: maximum recursion depth exceeded

原因: 函數遞歸調用自身,但沒有正確的終止條件,導致無限遞歸直到棧溢出。

# 錯誤:缺少終止條件
def countdown(n):
    print(n)
    countdown(n - 1)   # ← 沒有 n == 0 時停止的條件

countdown(5)   # 會一直遞歸到報錯

修復: 確保遞歸有明確的終止條件(base case):

def countdown(n):
    if n <= 0:         # ← 終止條件
        print("完成!")
        return
    print(n)
    countdown(n - 1)

countdown(5)

遇到報錯不知道怎麼改?

讀懂錯誤信息是第一步,但有時候還需要快速驗證修復思路。不想搭本地環境的話,直接把代碼粘到 Python 在線運行工具 裏跑一下,支持 Python 3.12,標準庫全覆蓋,Ctrl+Enter 直接執行,改完馬上能看到結果。

发现周边 发现周边
評論區

加載中...