新手必看!Python 初學者最容易犯的九個錯誤及解決方案
作者:用戶007
許多Python初學者在學習過程中會犯相同的錯誤。本文將通過真實案例,手把手教你識別并避免這些常見陷阱,讓你少走彎路,快速進階。
許多Python初學者在學習過程中會犯相同的錯誤。很多時候,這些都不是"真正的錯誤"(代碼能運行),而是不夠"Pythonic"的寫法。本文將通過真實案例,手把手教你識別并避免這些常見陷阱,讓你少走彎路,快速進階。

錯誤1:使用"=="比較布爾值
? 錯誤做法:
# 初學者常見寫法
is_active = True
if is_active == True: # 不pythonic
print("用戶已激活")
# 即使比較False也要這樣
if is_active == False:
print("用戶未激活")? 正確做法:
is_active = True
# 直接判斷真假值
if is_active:
print("用戶已激活")
# 判斷假值
ifnot is_active:
print("用戶未激活")
# 為什么這樣做更好?
# 1. 代碼更簡潔
# 2. 執行速度稍快
# 3. 符合Python哲學?? 擴展知識:
# Python中的"真"和"假"
# 這些值被認為是假(False):
falsy_values = [
False, # 布爾值False
None, # 空值
0, # 數字0
0.0, # 浮點數0
'', # 空字符串
[], # 空列表
{}, # 空字典
(), # 空元組
]
# 所有其他值都是真(True)
# 直接用if判斷能檢測這些值
if []: # 空列表被當作False
print("這不會執行")
else:
print("空列表是假值")
if [1, 2, 3]: # 非空列表是真
print("非空列表是真值")錯誤2:字符串拼接用"+"而不是f-string
? 錯誤做法:
name = "Alice"
age = 25
city = "Beijing"
# 老舊的字符串拼接方式
message1 = "My name is " + name + ", I'm " + str(age) + " years old, from " + city
print(message1)
# 或用format()方法(冗長)
message2 = "My name is {}, I'm {} years old, from {}".format(name, age, city)
print(message2)? 正確做法:
name = "Alice"
age = 25
city = "Beijing"
# Python 3.6+推薦:f-string(最簡潔最快)
message = f"My name is {name}, I'm {age} years old, from {city}"
print(message)
# f-string的強大之處
print(f"Age after 5 years: {age + 5}") # 直接計算
print(f"Name in uppercase: {name.upper()}") # 直接調用方法
print(f"Formatted number: {3.14159:.2f}") # 格式化數字
# 多行f-string
person_info = f"""
Name: {name}
Age: {age}
City: {city}
"""
print(person_info)錯誤3:手動打開/關閉文件而不用with語句
? 錯誤做法:
# 容易忘記關閉文件
file = open('data.txt', 'r')
content = file.read()
file.close() # 如果中間出錯,close()不會執行
# 或者出現異常時文件沒有正確關閉
file = open('data.txt', 'r')
content = file.read()
# 萬一這里崩潰,文件永遠不會關閉
print(content)
file.close()? 正確做法:
# 使用with語句(自動關閉文件)
with open('data.txt', 'r') as file:
content = file.read()
print(content)
# 即使發生異常,文件也會自動關閉
# 同時打開多個文件
with open('input.txt', 'r') as f_in, open('output.txt', 'w') as f_out:
for line in f_in:
f_out.write(line.upper())
# 對其他資源也適用
import json
with open('data.json', 'r') as f:
data = json.load(f)
# 數據庫連接
from sqlite3 import connect
with connect('database.db') as db:
cursor = db.cursor()
cursor.execute('SELECT * FROM users')錯誤4:使用可變默認參數
? 錯誤做法:
# 這是一個經典的Python陷阱
defadd_item(item, items_list=[]):
items_list.append(item)
return items_list
result1 = add_item('apple')
print(result1) # ['apple']
result2 = add_item('banana')
print(result2) # ['banana']??? 不!是['apple', 'banana']
# 為什么?因為默認參數只創建一次!
print(result1 is result2) # True(同一個列表)? 正確做法:
# 使用None作為默認值
defadd_item(item, items_list=None):
if items_list isNone:
items_list = []
items_list.append(item)
return items_list
result1 = add_item('apple')
print(result1) # ['apple']
result2 = add_item('banana')
print(result2) # ['banana']
print(result1 is result2) # False(不同的列表)
# 如果你確實想共享列表
shared_list = []
result1 = add_item('apple', shared_list)
result2 = add_item('banana', shared_list)
print(shared_list) # ['apple', 'banana']錯誤5:忘記列表切片不包含結束索引
? 錯誤做法:
numbers = [0, 1, 2, 3, 4, 5]
# 初學者以為這會得到[1, 2, 3, 4, 5]
result = numbers[1:5]
print(result) # [1, 2, 3, 4],沒有5!
# 初學者以為這會得到最后2個元素[4, 5]
result = numbers[-2] # 這會出錯,因為-2是倒數第二個元素
print(result) # 4? 正確做法:
numbers = [0, 1, 2, 3, 4, 5]
# 切片:[起始:結束),結束不包含
result = numbers[1:5] # [1, 2, 3, 4]
result = numbers[1:6] # [1, 2, 3, 4, 5]
# 獲取最后n個元素
result = numbers[-2:] # [4, 5]
result = numbers[-3:] # [3, 4, 5]
# 常用切片技巧
print(numbers[:]) # [0, 1, 2, 3, 4, 5] 復制整個列表
print(numbers[::2]) # [0, 2, 4] 每隔一個取一個
print(numbers[::-1]) # [5, 4, 3, 2, 1, 0] 反轉
print(numbers[1:4]) # [1, 2, 3]錯誤6:循環時使用索引獲取元素
# ? 初學者寫法
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
# ? 更pythonic的寫法
for fruit in fruits:
print(f"Fruit: {fruit}")
# ? 如果真的需要索引
for i, fruit in enumerate(fruits):
print(f"Index {i}: {fruit}")錯誤7:比較值時使用"is"而不是"=="
# ? 錯誤
if x is5: # is比較身份,不比較值
pass
if name is"Alice": # 這可能工作也可能不工作
pass
# ? 正確
if x == 5: # ==比較值
pass
if name == "Alice":
pass
# is只用于比較None、True、False
if x isNone:
pass
if flag isTrue: # 這樣可以,但if flag更好
pass錯誤8:異常處理太寬泛
# ? 太寬泛,隱藏真實錯誤
try:
user_age = int(input("Enter age: "))
print(100 / user_age)
except: # 捕獲所有異常!
print("Error")
# ? 精確捕獲
try:
user_age = int(input("Enter age: "))
print(100 / user_age)
except ValueError:
print("Please enter a valid number")
except ZeroDivisionError:
print("Age cannot be zero")
except Exception as e:
print(f"Unexpected error: {e}")錯誤9:在函數中修改全局變量而不聲明
# ? 容易出問題
counter = 0
defincrement():
counter = counter + 1# UnboundLocalError!
return counter
# ? 雖然能工作但不好
global_data = []
defadd_item(item):
global_data.append(item) # 直接修改全局變量
# ? 更好的做法
defincrement(counter):
return counter + 1
counter = 0
counter = increment(counter)
# ? 如果必須用全局變量
global_counter = 0
defincrement_global():
global global_counter # 明確聲明
global_counter += 1
# ? 最好的做法:使用類
classCounter:
def__init__(self):
self.value = 0
defincrement(self):
self.value += 1
return self.value
counter = Counter()
counter.increment()結尾
初學者犯的這些錯誤都是"學習的必經之路"。關鍵是要理解為什么這樣做是錯的,而不是單純地記住"應該這樣做"。當然,最好的學習方式就是在實踐中不斷犯錯、改正,最后形成習慣。
責任編輯:趙寧寧
來源:
Python數智工坊
























