Python初学者避坑指南(上篇)

1. 缩进不一致(空格与制表符混用)

错误代码

def func():
    print("Hello")  # 用4个空格
    print("World")  # 用制表符
# 报错:TabError: inconsistent use of tabs and spaces in indentation

正确做法:统一使用 4个空格(IDE可设置自动转换)。


2. 变量名覆盖内置关键字

错误代码

str = "Hello"  # 覆盖内置函数 str()
print(str(123))  # 报错:TypeError: 'str' object is not callable

正确做法:改用非保留字(如 my_str)。


3. 字符串引号未正确闭合或转义

错误代码

text = "He said "Hello""  # 引号冲突
# 报错:SyntaxError: invalid syntax

正确做法

text = "He said \"Hello\""  # 转义符
# 或
text = 'He said "Hello"'    # 交替引号

4. 误用 = 代替 == 进行比较

错误代码

x = 5
if x = 10:  # 报错:SyntaxError: invalid syntax
    print("Yes")

正确代码

if x == 10:
    print("Yes")

5. 可变对象作为函数默认参数

错误代码

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item(1))  # [1]
print(add_item(2))  # [1, 2](默认列表被共享!)

正确做法:用 None 代替默认可变对象:

def add_item(item, items=None):
    items = [] if items is None else items
    items.append(item)
    return items

6. 浮点数精度问题

错误代码

print(0.1 + 0.2 == 0.3)  # False(实际结果为 0.30000000000000004)

正确做法:使用 round 或 decimal 模块处理精度:

print(round(0.1 + 0.2, 1) == 0.3)  # True

7. 未处理类型转换异常

错误代码

num = int("123a")  # 报错:ValueError: invalid literal for int()

正确做法:捕获异常:

try:
    num = int("123a")
except ValueError:
    num = 0  # 设置默认值

8. 循环中修改列表长度

错误代码

lst = [1, 2, 3, 4]
for num in lst:
    if num % 2 == 0:
        lst.remove(num)  # 结果可能遗漏元素(如 [1, 3])

正确做法:遍历副本或新建列表:

for num in lst.copy():  # 或 lst[:]
    if num % 2 == 0:
        lst.remove(num)

9. if/elif/else 条件覆盖不全

错误代码

score = 85
if score >= 90:
    print("A")
if score >= 80:  # 多个 if 导致多次判断
    print("B")
else:
    print("C")
# 输出 B(但可能触发多个条件)

正确代码:用 elif 保证互斥:

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("C")

10. is 与 == 的误用

错误代码

a = [1, 2]
b = [1, 2]
print(a == b)  # True(值相等)
print(a is b)  # False(不是同一个对象)

正确场景is 用于判断 NoneTrueFalse 等单例对象。


11. 字符串拼接的低效操作

错误代码

s = ""
for i in range(1000):
    s += str(i)  # 频繁创建新对象,性能差

正确做法:用 join 或列表推导式:

s = "".join(str(i) for i in range(1000))

12. print 自动换行导致的格式混乱

错误代码

print("Loading", end="")
# 后续代码未换行,输出可能被覆盖

正确做法:合理使用 end 和 flush 参数:

print("Progress: 50%", end="\r", flush=True)

13. 忽略 None 的判断方式

错误代码

x = None
if x == None:  # PEP8 不推荐
    print("Empty")

正确做法:用 is 判断:

if x is None:
    print("Empty")

14. 布尔值的隐式转换陷阱

错误代码

if [] == False:  # False(空列表不等于 False)
    print("This is empty")

正确做法:直接判断是否为空:

if not []:
    print("This is empty")  # 正确触发

15. 模块导入顺序导致的依赖冲突

错误代码

# module_a.py
from module_b import func_b  # 若 module_b 也导入 module_a,引发循环导入

正确做法:重构代码或用局部导入:

def func_a():
    from module_b import func_b
    func_b()

16. 误用 import * 导致命名污染

错误代码

from math import *
print(sqrt(4))  # 2.0,但可能覆盖自定义的 sqrt 函数

正确做法:显式导入所需内容:

from math import sqrt

17. 未正确处理文件路径

错误代码

with open("data.txt") as f:  # 相对路径可能找不到文件
    pass

正确做法:动态获取路径:

import os
current_dir = os.path.dirname(__file__)
file_path = os.path.join(current_dir, "data.txt")

18. 误判作用域(未声明 global

错误代码

x = 10
def func():
    x += 1  # 报错:UnboundLocalError
func()

正确做法:使用 global 或非局部变量:

def func():
    global x
    x += 1

19. for 循环中的变量泄漏

错误代码

for i in range(3):
    pass
print(i)  # 输出 2(变量未销毁)

正确建议:避免依赖循环变量,或使用不同变量名。


20. 误用 and/or 替代条件判断

错误代码

x = 5
if x > 0 and < 10:  # 语法错误
    print("Valid")

正确代码

if 0 < x < 10:
    print("Valid")

总结一下吧!

上篇我们聊了基础语法里那些容易踩坑的高频陷阱,掌握它们能帮初学者省下不少调试的时间和烦恼。接下来,中篇会带你深入探索数据结构和函数的进阶难题,帮你更扎实地提升编程能力。最后,下篇则聚焦于工程实践中的高级误区,助你在真实项目中游刃有余。 一路跟着走,保证让你少走弯路,快速成长!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值