Python初学者常见错误详解
本文汇总了Python初学者最常遇到的12类错误,包括语法缺失、运算符误用、缩进规范、类型转换及作用域问题。通过对比错误代码与正确写法,帮助开发者快速定位并修复NameError、TypeError、IndentationError等异常,提升代码健壮性。
Python初学者常见错误详解
前言
Python 以简洁直观的语法著称,这与许多其他编程语言形成鲜明对比。然而,初学者往往容易忽略 Python 特有的规则,即使是有经验的程序员,也常受固有编程思维影响,写出不符合 Pythonic 风格的代码。本文整理了一位国外开发者总结的常见错误清单,并补充了个人理解与修正建议,旨在帮助读者规避这些陷阱。
语法与符号错误
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) 不会去全局查找,但因 print 时该变量尚未赋值,从而引发 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 定义时未接收 self 参数,因此报错。正确的调用方式应为 Foo.method1()。
需要注意的是,以上代码示例均基于 Python3。在 Python2 中,相同代码可能引发不同的错误,尤其是最后一个示例。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









