Python初学者避坑指南:16个常见运行时错误详解

Chloe
Chloe
发布时间:2026-10-12 | 3人浏览过
原创

本文总结了Python初学者最常遇到的16个运行时错误,涵盖语法、缩进、变量定义、字符串处理及类方法调用等核心问题。通过具体代码示例与错误分析,帮助开发者快速定位并修复NameError、KeyError、IndexError等异常,提升代码规范性与运行效率。

前言

Python凭借简洁直观的语法与其他编程语言形成鲜明对比,但初学者常因不熟悉Python特有规则而犯错,即便是有经验的程序员也易受固有思维影响,用其他语言的写法编写Python代码。此前曾分享过《Python新手容易犯的几个错误总结》,但内容尚不够全面。近期发现国外开发者总结了16个常见Python运行时错误(16 Common Python Runtime Errors Beginners Find),本文将该译文进行整理,并补充个人理解,旨在帮助读者避开这些常见陷阱。

0、忘记写冒号

在 if、elif、else、for、while、class、def 等语句末尾遗漏冒号 “:”

if spam == 42
 print('Hello!')

导致:SyntaxError: invalid syntax

1、误用 “=” 做等值比较

“=” 用于赋值操作,而判断两个值是否相等应使用 “==”

if spam = 42:
 print('Hello!')

导致:SyntaxError: invalid syntax

2、使用错误的缩进

Python依靠缩进区分代码块,常见错误用法如下:

print('Hello!')
 print('Howdy!')

导致:IndentationError: unexpected indent。同一代码块内的每行代码必须保持完全一致的缩进量

if spam == 42:
 print('Hello!')
 print('Howdy!')

导致:IndentationError: unindent does not match any outer indentation level。代码块结束后,缩进应恢复至原有层级

if spam == 42:
print('Hello!')

导致:IndentationError: expected an indented block。冒号 “:” 后必须使用缩进

3、变量没有定义

if spam == 42:
 print('Hello!')

导致:NameError: name 'spam' is not defined

4、获取列表元素索引位置忘记调用 len 方法

通过索引位置获取元素时,若忘记使用 len 函数获取列表长度,

spam = ['cat', 'dog', 'mouse']
for i in range(spam):
 print(spam[i])

导致:TypeError: range() integer end argument expected, got list。正确做法是:

spam = ['cat', 'dog', 'mouse']
for i in range(len(spam)):
 print(spam[i])

当然,更符合Python风格的写法是使用 enumerate

spam = ['cat', 'dog', 'mouse']
for i, item in enumerate(spam):
 print(i, item)

5、修改字符串

字符串是序列对象,支持索引访问,但与列表不同,字符串是不可变对象,不支持直接修改。

spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)

导致:TypeError: 'str' object does not support item assignment 正确做法应为:

spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)

6、字符串与非字符串连接

num_eggs = 12
print('I have ' + num_eggs + ' eggs.')

导致:TypeError: cannot concatenate 'str' and 'int' objects

将字符串与非字符串类型连接时,必须先将非字符串对象强制转换为字符串类型

num_eggs = 12
print('I have ' + str(num_eggs) + ' eggs.')

或者使用字符串的格式化方式

num_eggs = 12
print('I have %s eggs.' % (num_eggs))

7、使用错误的索引位置

spam = ['cat', 'dog', 'mouse']
print(spam[3])

导致:IndexError: list index out of range

列表索引从0开始,访问第3个元素应使用 spam[2]

8、字典中使用不存在的键

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

在字典对象中通过 [] 访问 key 时,若该 key 不存在,将导致:KeyError: 'zebra'

正确方式应使用 get 方法

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam.get('zebra'))

当 key 不存在时,get 默认返回 None

9、用关键字做变量名

class = 'algebra'

导致:SyntaxError: invalid syntax

Python不允许使用关键字作为变量名。Python3共有33个关键字。

>>> import keyword
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

10、函数中局部变量赋值前被使用

someVar = 42

def myFunction():
 print(someVar)
 someVar = 100

myFunction()

导致:UnboundLocalError: local variable 'someVar' referenced before assignment

当函数中存在与全局作用域同名的变量时,Python按LEGB规则查找。若在函数内部定义了同名变量,则不再向外层作用域查找。因此,在 myFunction 中 someVar 被定义后,print(someVar) 不再向外查找,但此时变量尚未赋值,从而引发 UnboundLocalError

11、使用自增 “++” 自减 “--”

spam = 0
spam++

Python中没有自增自减操作符,从C或Java转来的开发者需注意。可使用 “+=” 替代 “++”

spam = 0
spam += 1

12、错误地调用类中的方法

class Foo:
 def method1():
  print('m1')
 def method2(self):
  print("m2")

a = Foo()
a.method1()

导致:TypeError: method1() takes 0 positional arguments but 1 was given

method1 是 Foo 类的成员方法,不接受任何参数。调用 a.method1() 等价于 Foo.method1(a),但因 method1 不接受参数,故报错。正确调用方式应为 Foo.method1()。

需注意:以上代码均基于Python3,Python2中相同代码可能引发不同错误,尤其是最后一个示例。

总结

以上就是本文的全部内容,希望这些内容对您的Python学习或实际应用有所帮助。如有任何疑问,欢迎留言交流,感谢支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表