# Vibe Coder Recharge | Python > **目標**:能看懂 AI 生成的程式碼,知道它在做什麼,能提要求,能幫 AI 處理卡住 > **預估時間**:1-2 天(約 6-10 小時) > **學習平台**:[LearnPython.org](https://www.learnpython.org) --- ## 學習心法 ``` ┌─────────────────────────────────────────────────────────────────┐ │ │ │ 你不是要「會寫程式」,你是要: │ │ │ │ 1. 看懂 AI 寫的程式碼在做什麼 │ │ 2. 知道程式「能做到什麼」才能提出對的要求 │ │ 3. AI 卡住時,看懂錯誤訊息,給 AI 有用的提示 │ │ │ │ 所以: │ │ ✓ 概念要懂 │ │ ✓ 不用背語法(AI 會寫) │ │ ✓ 練習「讀」比練習「寫」更重要 │ │ │ └─────────────────────────────────────────────────────────────────┘ ``` --- ## Part 1:Python 基礎語法 ### 1.1 基礎篇(必做)— 約 2-3 小時 | 順序 | 章節 | 連結 | 重要性 | 備註 | |------|------|------|--------|------| | 1 | Hello, World! | [連結](https://www.learnpython.org/en/Hello%2C_World%21) | ⭐⭐ | 了解 print、程式怎麼跑 | | 2 | Variables and Types | [連結](https://www.learnpython.org/en/Variables_and_Types) | ⭐⭐⭐ | 字串、數字、布林,必懂 | | 3 | Lists | [連結](https://www.learnpython.org/en/Lists) | ⭐⭐⭐ | 超常用的資料結構 | | 4 | Basic Operators | [連結](https://www.learnpython.org/en/Basic_Operators) | ⭐⭐ | +, -, *, /, %, == | | 5 | Conditions | [連結](https://www.learnpython.org/en/Conditions) | ⭐⭐⭐ | if/elif/else,必懂 | | 6 | Loops | [連結](https://www.learnpython.org/en/Loops) | ⭐⭐⭐ | for/while,必懂 | | 7 | Functions | [連結](https://www.learnpython.org/en/Functions) | ⭐⭐⭐ | def,核心概念 | | 8 | Dictionaries | [連結](https://www.learnpython.org/en/Dictionaries) | ⭐⭐⭐ | key-value,JSON 的基礎 | ### 1.2 略讀篇(快速看過)— 約 1 小時 | 順序 | 章節 | 連結 | 備註 | |------|------|------|------| | 9 | String Formatting | [連結](https://www.learnpython.org/en/String_Formatting) | f-string 很常見,知道 `f"{變數}"` 就好 | | 10 | Basic String Operations | [連結](https://www.learnpython.org/en/Basic_String_Operations) | 字串處理,快速瀏覽 | | 11 | Classes and Objects | [連結](https://www.learnpython.org/en/Classes_and_Objects) | 了解 class 概念,AI 常用 | | 12 | Modules and Packages | [連結](https://www.learnpython.org/en/Modules_and_Packages) | import 怎麼運作 | ### 1.3 可跳過 | 章節 | 原因 | |------|------| | ~~Input and Output~~ | 檔案讀寫,用到再學 | --- ## Part 2:進階概念(Vibe Coding 常遇到) ### 2.1 重要!必須理解 — 約 1-2 小時 | 順序 | 章節 | 連結 | 重要性 | 為什麼重要 | |------|------|------|--------|-----------| | 1 | List Comprehensions | [連結](https://www.learnpython.org/en/List_Comprehensions) | ⭐⭐⭐ | AI 超愛用這個語法 `[x for x in list]` | | 2 | Lambda functions | [連結](https://www.learnpython.org/en/Lambda_functions) | ⭐⭐⭐ | 匿名函數,AI 常寫 `lambda x: x*2` | | 3 | Exception Handling | [連結](https://www.learnpython.org/en/Exception_Handling) | ⭐⭐⭐ | try/except,處理錯誤必備 | | 4 | Map, Filter, Reduce | [連結](https://www.learnpython.org/en/Map%2C_Filter%2C_Reduce) | ⭐⭐ | 資料處理常見模式 | ### 2.2 略讀即可 — 約 30 分鐘 | 章節 | 連結 | 備註 | |------|------|------| | Multiple Function Arguments | [連結](https://www.learnpython.org/en/Multiple_Function_Arguments) | *args, **kwargs,看過就好 | | Regular Expressions | [連結](https://www.learnpython.org/en/Regular_Expressions) | 正規表達式,概念知道就好 | | Decorators | [連結](https://www.learnpython.org/en/Decorators) | @decorator 語法,知道是什麼 | ### 2.3 可之後再學 | 章節 | 原因 | |------|------| | ~~Generators~~ | 進階概念,用到再學 | | ~~Sets~~ | 集合,用到再查 | | ~~Serialization~~ | JSON 處理,用到再查 | | ~~Partial functions~~ | 很少用 | | ~~Code Introspection~~ | 很少用 | | ~~Closures~~ | 進階概念 | | ~~Parsing CSV Files~~ | 用 Pandas 比較實用 | --- ## Part 3:Pandas 基礎(n8n 數據處理必備) > Pandas 不在 LearnPython.org,但 Vibe Coding 處理數據必備 ### 3.1 為什麼要學 Pandas? ``` ┌─────────────────────────────────────────────────────────────────┐ │ │ │ n8n 的 Code Node 處理數據時,Pandas 是標配: │ │ │ │ - 篩選資料:df[df['score'] < 3] │ │ - 分組統計:df.groupby('category').mean() │ │ - 合併資料:pd.merge(df1, df2, on='id') │ │ │ │ 這些用純 Python 寫會很痛苦 │ │ │ └─────────────────────────────────────────────────────────────────┘ ``` ### 3.2 Pandas 10 分鐘入門 **推薦資源**:[Pandas 10 minutes tutorial](https://pandas.pydata.org/docs/user_guide/10min.html) **必須知道的操作**(在 Jupyter 試一試): ```python import pandas as pd # 1. 建立 DataFrame(表格) df = pd.DataFrame({ 'name': ['Alice', 'Bob', 'Charlie'], 'score': [85, 72, 91], 'department': ['Sales', 'IT', 'Sales'] }) # 2. 看資料 df.head() # 看前幾筆 df.info() # 看欄位型態 df.describe() # 看統計摘要 # 3. 選取欄位 df['name'] # 單一欄位 df[['name', 'score']] # 多個欄位 # 4. 篩選資料 df[df['score'] > 80] # 分數大於 80 的 df[df['department'] == 'Sales'] # Sales 部門的 # 5. 分組統計 df.groupby('department')['score'].mean() # 各部門平均分 # 6. 新增欄位 df['passed'] = df['score'] >= 60 # 7. 排序 df.sort_values('score', ascending=False) ``` ### 3.3 Pandas 在 n8n 的應用模式 ```python # n8n Code Node 典型模式 import pandas as pd # 1. 接收 n8n 傳來的資料 input_data = $input.all() records = [item['json'] for item in input_data] # 2. 轉成 DataFrame df = pd.DataFrame(records) # 3. 處理(篩選、統計、轉換) result = df[df['status'] == 'active'].groupby('category').size() # 4. 轉回 n8n 格式 return [{'json': result.to_dict()}] ``` --- ## Part 4:常見程式碼模式(AI 愛用的寫法) > 這些不用會寫,但要看得懂 ### 4.1 List Comprehension(列表推導式) ```python # AI 很常寫這樣 names = [user['name'] for user in users] # 等於這樣(但 AI 不會這樣寫) names = [] for user in users: names.append(user['name']) ``` ### 4.2 Lambda + Map/Filter ```python # AI 常寫 scores = list(map(lambda x: x * 1.1, raw_scores)) # 等於 scores = [x * 1.1 for x in raw_scores] ``` ### 4.3 Dictionary Comprehension ```python # AI 常寫 user_map = {u['id']: u['name'] for u in users} # 等於 user_map = {} for u in users: user_map[u['id']] = u['name'] ``` ### 4.4 Try/Except 錯誤處理 ```python # AI 標準寫法 try: result = risky_operation() except Exception as e: print(f"Error: {e}") result = default_value ``` ### 4.5 F-string 格式化 ```python # AI 愛用 name = "Alice" score = 85 message = f"{name} 的分數是 {score} 分" # 老寫法(你可能會看到) message = "{} 的分數是 {} 分".format(name, score) message = "%s 的分數是 %d 分" % (name, score) ``` ### 4.6 解構賦值 ```python # AI 常寫 first, *rest = my_list name, age = user_tuple # 字典解構 data = {'a': 1, 'b': 2} a = data.get('a', 0) # 有預設值的取法 ``` ### 4.7 Walrus Operator(:=) ```python # Python 3.8+ AI 可能會用 if (n := len(users)) > 10: print(f"有 {n} 個用戶") ``` --- ## Part 5:看懂錯誤訊息 > AI 卡住時,你要能看懂錯誤,給 AI 有用的提示 ### 5.1 常見錯誤類型 | 錯誤類型 | 常見原因 | 怎麼告訴 AI | |---------|---------|------------| | `SyntaxError` | 語法寫錯(括號、冒號) | 「第 X 行語法錯誤,請檢查」 | | `NameError` | 變數未定義 | 「變數 XXX 沒有定義,是不是沒 import?」 | | `TypeError` | 型態不對(字串當數字用) | 「這裡型態錯了,XXX 是字串不是數字」 | | `KeyError` | 字典沒這個 key | 「字典裡沒有 XXX 這個 key」 | | `IndexError` | 陣列超出範圍 | 「陣列只有 X 個元素,但取第 Y 個」 | | `AttributeError` | 物件沒這個方法 | 「XXX 沒有 YYY 這個方法」 | | `ImportError` | 套件沒裝或名字錯 | 「是不是沒安裝 XXX?或名字打錯?」 | | `ValueError` | 值不對 | 「傳入的值不符合預期」 | ### 5.2 看錯誤訊息的技巧 ```python # 錯誤訊息範例 Traceback (most recent call last): File "main.py", line 15, in <module> ← 錯在第 15 行 result = process_data(data) File "main.py", line 8, in process_data ← 從這裡呼叫的 return data['name'].upper() KeyError: 'name' ← 錯誤類型和原因 ``` **給 AI 的有效提示**: ``` 「執行到 process_data 函數的第 8 行時出錯, KeyError: 'name', data 裡面沒有 'name' 這個 key。 我的 data 結構是 {'username': 'xxx', ...}, 請修正」 ``` ### 5.3 Debug 小技巧 ```python # 印出變數內容(最基本的 debug) print(f"data = {data}") print(f"type = {type(data)}") print(f"keys = {data.keys()}") # 確認到底有什麼 import json print(json.dumps(data, indent=2, ensure_ascii=False)) ``` --- ## Part 6:學習完成檢核表 ### 基礎語法(必須打勾) - [ ] 我知道 `def` 是定義函數 - [ ] 我知道 `if/elif/else` 是條件判斷 - [ ] 我知道 `for item in list` 是遍歷 - [ ] 我知道 `list`(清單)和 `dict`(字典)的差別 - [ ] 我知道 `import` 是引入套件 ### 進階模式(看得懂就好) - [ ] 我看得懂 `[x for x in list]` 是在做什麼 - [ ] 我看得懂 `lambda x: x*2` 是匿名函數 - [ ] 我看得懂 `try/except` 是在處理錯誤 - [ ] 我看得懂 `f"{變數}"` 是字串格式化 ### Pandas(會用就好) - [ ] 我知道 `pd.DataFrame(data)` 是建立表格 - [ ] 我知道 `df[df['col'] > 10]` 是篩選 - [ ] 我知道 `df.groupby('col').sum()` 是分組統計 ### 錯誤處理(能看懂) - [ ] 我知道看錯誤訊息的「最後幾行」最重要 - [ ] 我知道 `KeyError` 是字典沒這個 key - [ ] 我知道 `TypeError` 是型態用錯了 - [ ] 我能把錯誤訊息「翻譯」成給 AI 的提示 --- ## 學習路徑總覽 ```mermaid flowchart TB subgraph Day1["第一天(4-5 小時)"] A1[基礎語法] --> A2[Variables, Lists, Dicts] A2 --> A3[Conditions, Loops] A3 --> A4[Functions] A4 --> A5[略讀:Classes, Modules] end subgraph Day2["第二天(3-4 小時)"] B1[進階模式] --> B2[List Comprehension] B2 --> B3[Lambda, Map/Filter] B3 --> B4[Exception Handling] B4 --> B5[Pandas 基礎] end subgraph Practice["實戰練習"] C1[在 Jupyter 試跑] C2[看 AI 生成的程式碼] C3[故意製造錯誤,練習看錯誤訊息] end Day1 --> Day2 --> Practice ``` --- ## 附錄:快速參考卡 ### 資料結構 ```python # List(清單)— 有順序,可重複 fruits = ['apple', 'banana', 'apple'] fruits[0] # 'apple' fruits.append('orange') len(fruits) # 4 # Dict(字典)— key-value 對應 user = {'name': 'Alice', 'age': 30} user['name'] # 'Alice' user.get('email', 'N/A') # 'N/A'(有預設值) user.keys() # dict_keys(['name', 'age']) # Tuple(元組)— 不可改的 list point = (10, 20) x, y = point # 解構 ``` ### 常用內建函數 ```python len(list) # 長度 range(10) # 0-9 enumerate(list) # 帶 index 的迴圈 zip(list1, list2) # 配對兩個 list sorted(list) # 排序(不改原本的) list.sort() # 排序(改原本的) ``` ### 字串處理 ```python s = "Hello World" s.lower() # 'hello world' s.upper() # 'HELLO WORLD' s.split(' ') # ['Hello', 'World'] s.replace('o', '0')# 'Hell0 W0rld' s.strip() # 去頭尾空白 '|'.join(['a','b'])# 'a|b' ``` ### 常用 import ```python import json # JSON 處理 import re # 正規表達式 import datetime # 日期時間 import os # 作業系統 import pandas as pd # 資料處理 import requests # HTTP 請求 ``` --- *目標:不是成為 Python 工程師,是成為能有效指揮 AI 的 Vibe Coder*