Skip to content

错误类型

认识 Python 的常见错误


错误 vs 异常

  • 语法错误(Syntax Error):代码写错,无法运行
  • 异常(Exception):运行时发生的错误

常见语法错误

1. 缩进错误

python
#  IndentationError
def greet():
print("Hello")  # 缺少缩进

#  正确
def greet():
    print("Hello")

2. 冒号缺失

python
#  SyntaxError
if age > 18  # 缺少冒号
    print("Adult")

#  正确
if age > 18:
    print("Adult")

3. 括号不匹配

python
#  SyntaxError
result = (1 + 2  # 缺少右括号

#  正确
result = (1 + 2)

常见运行时异常

1. NameError:变量未定义

python
print(age)  # NameError: name 'age' is not defined

# 正确:先定义再使用
age = 25
print(age)

2. TypeError:类型错误

python
# 示例 1:不同类型运算
result = "25" + 5  # TypeError: can only concatenate str

# 正确
result = int("25") + 5  # 30

# 示例 2:参数类型错误
def greet(name):
    print(f"Hello, {name}")

greet(123)  # 可运行,但不推荐

3. ValueError:值错误

python
# 示例 1:类型转换失败
age = int("abc")  # ValueError: invalid literal

# 示例 2:列表方法找不到值
lst = [1, 2, 3]
lst.remove(5)  # ValueError: 5 not in list

4. IndexError:索引超出范围

python
ages = [25, 30, 35]
print(ages[5])  # IndexError: list index out of range

# 正确
if len(ages) > 5:
    print(ages[5])

5. KeyError:字典键不存在

python
student = {'name': 'Alice', 'age': 25}
print(student['major'])  # KeyError: 'major'

# 正确方法
print(student.get('major', 'Unknown'))  # Unknown

6. FileNotFoundError:文件不存在

python
with open('non_existent.txt', 'r') as f:  # FileNotFoundError
    content = f.read()

# 正确:先检查
from pathlib import Path
if Path('file.txt').exists():
    with open('file.txt', 'r') as f:
        content = f.read()

7. ZeroDivisionError:除以零

python
result = 10 / 0  # ZeroDivisionError

# 正确
if denominator != 0:
    result = numerator / denominator

8. AttributeError:属性不存在

python
lst = [1, 2, 3]
lst.append(4)      #  列表有 append
lst.push(5)        #  AttributeError: 'list' object has no attribute 'push'

社科场景的常见错误

场景 1:数据清洗

python
# 读取问卷数据
data = [
    {'id': 1, 'age': '25', 'income': '50000'},
    {'id': 2, 'age': 'N/A', 'income': '75000'},
    {'id': 3, 'age': '35', 'income': 'unknown'}
]

#  直接转换会出错
for resp in data:
    age = int(resp['age'])  # ValueError at id=2

场景 2:文件读取

python
#  文件可能不存在
df = pd.read_csv('survey_2024.csv')  # FileNotFoundError

#  列名可能拼写错误
mean_income = df['imcome'].mean()  # KeyError: 'imcome'

场景 3:API 调用

python
import requests

#  网络可能断开
response = requests.get('https://api.example.com/data')
data = response.json()  # 可能失败

查看错误信息

python
# 完整的错误信息示例
ages = [25, 30, 35]
print(ages[5])

# 输出:
# Traceback (most recent call last):
#   File "script.py", line 2, in <module>
#     print(ages[5])
# IndexError: list index out of range

解读

  • Traceback:错误追踪
  • File "script.py", line 2:出错位置
  • IndexError:错误类型
  • list index out of range:错误描述

预防错误

1. 使用类型提示

python
def calculate_mean(data: list) -> float:
    """计算平均值"""
    return sum(data) / len(data)

2. 输入验证

python
def calculate_tax(income):
    if not isinstance(income, (int, float)):
        raise TypeError("收入必须是数字")
    if income < 0:
        raise ValueError("收入不能为负数")
    return income * 0.25

3. 使用安全的方法

python
#  不安全
value = dict[key]

#  安全
value = dict.get(key, default_value)

练习题

python
# 找出以下代码的错误类型

# 1.
result = "25" + 5

# 2.
ages = [25, 30, 35]
print(ages[3])

# 3.
def greet()
    print("Hello")

# 4.
student = {'name': 'Alice'}
print(student['age'])

# 5.
value = int("abc")

下一步

下一节学习如何使用 try-except 捕获和处理这些错误。

继续!

基于 MIT 许可证发布。内容版权归作者所有。