土薯工具 Toolshu.com 登录 用户注册

Python 新手最常犯的 10 个错误:报错原因与修复方法

原创 作者:bhnw 于 2026-04-09 13:11 发布 2次浏览 收藏 (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 直接执行,改完马上能看到结果。

发现周边 发现周边
评论区

加载中...