前言
帶過幾年初學者,發現大家踩到的坑幾乎都一樣。這篇整理了最常見的 5 個錯誤,不是要罵人,是因為這些問題真的每週都在課堂上看到。
錯誤 1:縮排混用 Tab 和空格
Python 對縮排超嚴格,而且 Tab 和空格混用會讓你看起來沒問題,執行時卻炸掉。
# 這樣會 IndentationError
def my_func():
print("hello") # 4 個空格
print("world") # 1 個 Tab ← 問題在這解法:在 VS Code 設定「Render Whitespace」,或直接用「Convert Indentation to Spaces」統一格式。
錯誤 2:字串和數字直接相加
age = input("請輸入年齡:") # input() 回傳的是字串
print("明年你會是" + age + 1 + "歲") # TypeError!解法:記住 input() 永遠回傳字串,要用 int() 或 float() 轉換。
age = int(input("請輸入年齡:"))
print(f"明年你會是 {age + 1} 歲") # 用 f-string 最乾淨錯誤 3:把 list 當 copy 用
a = [1, 2, 3]
b = a # 這不是複製!b 和 a 指向同一個 list
b.append(4)
print(a) # [1, 2, 3, 4] ← a 也被改了解法:用切片或 copy() 做真正的複製。
b = a[:] # 或 b = a.copy()錯誤 4:在迴圈裡改 list
nums = [1, 2, 3, 4, 5]
for n in nums:
if n % 2 == 0:
nums.remove(n) # 邊走邊刪,結果不對
print(nums) # [1, 3, 5]?不一定解法:用串列推導式建立新的 list。
nums = [n for n in nums if n % 2 != 0]錯誤 5:不處理例外,程式一碰到奇怪輸入就掛掉
# 使用者輸入 "abc",int() 就 ValueError
score = int(input("輸入分數:"))解法:養成 try/except 的習慣。
try:
score = int(input("輸入分數:"))
except ValueError:
print("請輸入數字!")
score = 0總結
這 5 個錯誤不是因為你不夠聰明,是因為 Python 有幾個跟其他語言不一樣的地方。踩過一次,記住了,後面就順很多。