2025年2月15日 星期六

5 Common Python Mistakes and How to Fix Them – Summary

5 Common Python Mistakes and How to Fix Them – Summary

  1. 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 pylint can catch indentation errors early.
  2. 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.
  3. 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.
  4. 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 None as a default argument and create a new object inside the function.
  5. 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.
  6. Bad Import Practices (22:24 - 24:08)

    • from module import * can overwrite existing functions and make debugging difficult.
    • Better practice: Use import module or 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 檔案並寫入:
    print("This is my math module")
    
    再在另一個 Python 檔案中執行:
    from math import sqrt
    print(sqrt(16))
    
    會發生:
    ImportError: cannot import name 'sqrt' from 'math'
    

解決方法:

  • 不要將 Python 檔案命名為標準函式庫的名稱 (如 math.pyrandom.pydatetime.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 初學者和中級開發者經常犯的,透過了解這些問題和修正方法,可以有效避免程式執行時發生意外的錯誤!

沒有留言:

張貼留言

精選文章

手機使用VPN進入NAS、DaikinAPP時,仍能使用其他APP如銀行,連上WIFI 或行動網路

為了避免手機使用VPN進入NAS、DaikinAPP時,仍能使用其他APP如銀行,連上WIFI 或行動網路,要修改Router Policy設定?需要把家中屬於VPN的網段設備與其他區隔?要如何設定? 為了達成您的需求: ✅ 手機連上 VPN(例如連回家中 TP-Link ER...