5 Common Python Mistakes and How to Fix Them – Summary
-
Mixing Tabs and Spaces (00:48 - 03:49)
- Beginners often mix tabs and spaces, leading to indentation errors.
- Using a proper editor (VS Code, PyCharm, Sublime Text) that auto-converts tabs to spaces prevents this issue.
- Tools like
pylintcan catch indentation errors early.
-
Naming Files the Same as Standard Library Modules (04:20 - 06:35)
- Naming a file the same as a built-in module (e.g.,
math.py) causes import conflicts. - Python prioritizes local files over standard library modules, leading to import errors.
- Renaming the file resolves the issue.
- Naming a file the same as a built-in module (e.g.,
-
Overwriting Built-in Functions with Variables (07:32 - 09:39)
- Assigning a variable the same name as a built-in function (e.g.,
radians = radians(90)) makes the function inaccessible. - This causes "float object is not callable" errors.
- Using distinct variable names prevents conflicts.
- Assigning a variable the same name as a built-in function (e.g.,
-
Mutable Default Arguments in Functions (10:43 - 16:21)
- Using mutable objects (e.g., lists, dictionaries) as default function arguments causes unexpected behavior.
- Python evaluates default arguments only once, so modifications persist across function calls.
- Fix: Use
Noneas a default argument and create a new object inside the function.
-
Iterator Exhaustion (18:01 - 21:20)
- In Python 3, functions like
zip()return iterators instead of lists. - Iterators can only be traversed once, leading to unexpected empty results on subsequent accesses.
- Solution: Convert iterators to lists (
list(zip(names, superheroes))) before looping multiple times.
- In Python 3, functions like
-
Bad Import Practices (22:24 - 24:08)
from module import *can overwrite existing functions and make debugging difficult.- Better practice: Use
import moduleor explicitly import only necessary functions.
These common mistakes are easy to avoid with good coding practices and awareness of Python's behavior.
以下是 「5 個常見的 Python 錯誤及其修正方法」 的摘要,並搭配影片中的實際例子說明:
1. 混用 Tab 和空格導致縮排錯誤 (00:48)
錯誤:
- 初學者常混用 Tab 和 空格 來縮排 Python 程式碼,導致 IndentationError。
- 例如:
執行時會出現:for i in range(5): print(i) # 使用 4 個空格縮排 print(i * 2) # 這行使用 Tab,會產生錯誤IndentationError: unindent does not match any outer indentation level
解決方法:
- 使用支援自動轉換縮排的編輯器 (如 VS Code、PyCharm、Sublime Text)。
- 在 Sublime Text 中可設定
translate_tabs_to_spaces: true來確保統一使用空格。
2. 命名 Python 檔案與標準函式庫名稱相同 (04:20)
錯誤:
- 若命名 Python 檔案為
math.py,然後嘗試import math,會導致導入的不是標準函式庫,而是自己寫的檔案。 - 例如,建立
math.py檔案並寫入:
再在另一個 Python 檔案中執行:print("This is my math module")
會發生:from math import sqrt print(sqrt(16))ImportError: cannot import name 'sqrt' from 'math'
解決方法:
- 不要將 Python 檔案命名為標準函式庫的名稱 (如
math.py、random.py、datetime.py等)。 - 若已命名錯誤,請 更改檔案名稱 並刪除對應的
.pyc檔案或__pycache__資料夾。
3. 變數覆蓋內建函數或模組 (07:32)
錯誤:
- 若變數名稱與內建函數名稱相同,可能導致函數無法使用。
- 例如:
會發生:radians = 1.57 # radians 原本是 math 模組的函數 print(radians(90)) # 嘗試調用 radians 函數TypeError: 'float' object is not callable
解決方法:
- 避免將變數命名為 Python 內建函數名稱,例如:
rads = 1.57 # 使用 rads 而非 radians
4. 可變物件作為函數的預設參數 (10:43)
錯誤:
- 若將 可變物件 (如 list 或 dict) 設為函數預設參數,會導致意想不到的行為:
預期應該每次都回傳新列表,但結果卻是前一次的資料還在。def add_employee(employee, emp_list=[]): # 預設參數為空列表 emp_list.append(employee) return emp_list print(add_employee("Alice")) # ['Alice'] print(add_employee("Bob")) # ['Alice', 'Bob']
解決方法:
- 使用
None作為預設值,並在函數內建立新列表:def add_employee(employee, emp_list=None): if emp_list is None: emp_list = [] emp_list.append(employee) return emp_list
5. 迭代器 (Iterator) 被意外耗盡 (19:10)
錯誤:
zip()、map()等函數返回的是迭代器,只能使用一次:names = ["Peter", "Clark"] heroes = ["Spider-Man", "Superman"] identity_pairs = zip(names, heroes) print(list(identity_pairs)) # [('Peter', 'Spider-Man'), ('Clark', 'Superman')] print(list(identity_pairs)) # [] 因為迭代器已經被耗盡
解決方法:
- 若需要多次使用結果,請將其轉換為
list:identity_pairs = list(zip(names, heroes))
這些錯誤都是 Python 初學者和中級開發者經常犯的,透過了解這些問題和修正方法,可以有效避免程式執行時發生意外的錯誤!
沒有留言:
張貼留言