# Python程式筆記 有著興趣就去學了一下,希望之後可以在這個領域更加進步,有網路爬蟲、搶票那些都是用Python就想著先學一些,等之後競賽完有更多空閒的時候就可以去學:D >thx GPT [TOC] ## 下載 [下載操作步驟(巨匠電腦)](https://www.pcschool.com.tw/blog/it/python-installation) ✅特別注意:記得勾選Add Python to PATH!!! ![image](https://hackmd.io/_uploads/BkfaXhnglx.png) ## 輸入 ```python # 基本語法 變數 = input("提示文字:") ``` --- ### 🎯 一、`input()` 的基本功能 | 功能 | 說明 | 範例 | | --------------- | ----------------- | ---------------------------------- | | `input()` | 從鍵盤讀取字串(String) | `name = input("請輸入姓名:")` | | `input("提示文字")` | 顯示提示訊息 | `x = input("請輸入數字:")` | | 所有輸入都是字串型別 | 即使輸入數字,也會變成 `str` | `type(input("1")) → <class 'str'>` | --- ### 🔢 二、輸入後轉型(型別轉換) | 用法 | 功能 | 範例 | | ---------------- | ----------- | ---------------------------- | | `int(input())` | 轉為整數 | `a = int(input("請輸入整數:"))` | | `float(input())` | 轉為浮點數 | `b = float(input("請輸入身高:"))` | | `str(input())` | 轉為字串(通常不需要) | `c = str(input("請輸入文字:"))` | | `eval(input())` | 自動判斷型別(慎用) | 輸入 `3.14` → 變成 float | 🟡 **小陷阱:** ```python a = input("請輸入數字:") # 例如輸入 5 print(a * 2) # 結果是 '55',不是 10! ``` ✅ 正確寫法: ```python a = int(input("請輸入數字:")) print(a * 2) # 結果是 10 ``` --- ### ✨ 三、多筆輸入(同一行) | 語法 | 說明 | 範例 | | -------------------- | ------- | ---------------------------------------- | | `input().split()` | 以空白分開輸入 | `a,b = input("輸入兩數:").split()` | | `input().split(',')` | 以逗號分隔輸入 | `a,b = input("輸入兩數(逗號分隔):").split(',')` | | `map()` + 型別轉換 | 同時轉型 | `a,b = map(int, input("輸入兩數:").split())` | ✅ **範例:** ```python a, b, c = map(int, input("輸入三個整數:").split()) print(a + b + c) ``` --- ### 🧮 四、輸入計算應用範例 #### BMI 計算 ```python h = float(input("輸入身高(cm):")) / 100 w = float(input("輸入體重(kg):")) bmi = w / (h ** 2) print(f"BMI = {bmi:.2f}") ``` #### 成績平均 ```python scores = list(map(int, input("輸入五科成績:").split())) print("平均分數:", sum(scores)/len(scores)) ``` --- ### 🧰 五、字串處理與輸入搭配 | 功能 | 語法 | 範例 | | -------------- | --------- | ----------------------------------- | | `strip()` | 去除前後空白與換行 | `name = input().strip()` | | `lower()` | 全轉小寫 | `ans = input("是否繼續(y/n)?").lower()` | | `upper()` | 全轉大寫 | `ans = input("是否繼續(y/n)?").upper()` | | `capitalize()` | 首字母大寫 | `day = input("輸入星期:").capitalize()` | ✅ **例:** ```python ans = input("是否繼續(y/n)? ").lower() if ans == 'y': print("繼續!") else: print("結束!") ``` --- ### ⚙️ 六、防呆與例外處理 | 語法 | 說明 | | --------------- | --------- | | `try...except:` | 防止輸入非數字錯誤 | | `isdigit()` | 檢查是否全為數字 | ✅ **例:** ```python x = input("請輸入整數:") if x.isdigit(): x = int(x) print(x**2) else: print("輸入錯誤,請輸入整數!") ``` ✅ **try-except 範例:** ```python try: n = int(input("輸入整數:")) print(f"平方:{n*n}") except ValueError: print("請輸入正確的數字!") ``` --- ### 📚 七、綜合例題:查詢系統 ```python item_list = ["可樂", "果汁", "紅茶"] item = input("輸入要查詢的品項:") if item in item_list: print(f"已存在:{item}") else: add = input("查無此項,是否新增?(y/n): ").lower() if add == 'y': item_list.append(item) print("已新增!") print(item_list) ``` --- ### 💡 八、考試常見錯誤整理 | 錯誤 | 錯誤原因 | 正確寫法 | | ------------------------------------------------- | --------------- | --------------------------------------------- | | `TypeError: can only concatenate str (not "int")` | 用字串加整數 | `str(a)` 或轉型 | | `ValueError: invalid literal for int()` | 輸入非數字卻用 `int()` | 加 `try/except` | | `NameError` | 變數沒宣告或拼錯 | 檢查拼字 | | `if a=="Y" or "y":` | 錯誤邏輯,始終為 True | `if a=='Y' or a=='y':` 或 `if a.lower()=='y':` | --- ### 🎓 九、進階補充 | 主題 | 說明 | | --------------- | ----------------------------------------- | | `input()` 只能讀單行 | 多行輸入需用 `for` 或 `while` | | 批次輸入 | `for i in range(n): data.append(input())` | | 自動分割與轉型 | `list(map(int, input().split()))` | --- ### 🔚 十、總結重點 1. `input()` 讀進來 **都是字串**。 2. 要運算必須 `int()` 或 `float()` 轉型。 3. 多筆輸入用 `split()`。 4. 判斷選項建議搭配 `.lower()` 或 `.upper()`。 5. 錯誤處理可用 `try-except`。 ## 輸出 ```python= print("Hello, world!") ``` 📌 print() 可以印出字串、數字、變數、運算結果等等。 ## 各類輸出方式 ## 🧩 一、f-string(Python 3.6+ 推薦用法) **最直覺、最推薦的方式**,支援變數插值與運算。 ```python name = "小明" age = 18 print(f"{name}你好,今年{age}歲!") print(f"{name}明年會變成{age + 1}歲。") ``` **優點:** * 可直接運算、支援函式呼叫。 * 可搭配格式化語法(小數點、對齊等)。 ```python pi = 3.14159 print(f"圓周率約為 {pi:.2f}") # 3.14 print(f"{'右對齊':>6}") # 右對齊 ``` --- ## 🧮 二、舊式 `%` 格式化(C 風格) 早期的格式化方式(Python 2 時代沿用下來)。 ```python name = "小明" age = 18 print("%s你好,今年%d歲!" % (name, age)) ``` **常見格式符號:** | 符號 | 意義 | | ---- | ---- | | `%s` | 字串 | | `%d` | 整數 | | `%f` | 浮點數 | | `%x` | 十六進位 | **範例:** ```python pi = 3.14159 print("圓周率約為 %.2f" % pi) # 3.14 ``` --- ## 🧱 三、`str.format()` 方法(Python 2.6+) 比 `%` 多功能,可指定位置或變數名。 ```python name = "小明" age = 18 print("{}你好,今年{}歲!".format(name, age)) print("{1}你好,今年{0}歲!".format(age, name)) # 指定位置 print("{n}你好,今年{a}歲!".format(n=name, a=age)) # 指定名稱 ``` **格式化控制:** ```python pi = 3.14159 print("圓周率約為 {:.2f}".format(pi)) print("{:>10}".format("右對齊")) # 寬度10右對齊 ``` --- ## 🧾 四、字串串接與輸出 最基本的做法,直接用 `+` 或 `,` 串接。 ```python name = "小明" age = 18 print(name + "你好,今年" + str(age) + "歲!") print(name, "你好,今年", age, "歲!") # 逗號自動加空格 ``` --- ## 🧰 五、進階用法與補充 ### 1. 多行字串輸出 ```python print(f""" 嗨,{name}! 你的年齡是 {age} 歲。 """) ``` ### 2. 結合變數與格式化設定 ```python num = 1234.5678 print(f"{num:,.2f}") # 千分位 + 小數兩位 → 1,234.57 ``` ### 3. 使用 `print()` 的參數 ```python print("A", "B", "C", sep="-") # A-B-C print("這行不換行", end=" ") print("接著這行") ``` --- ## ✅ 總結比較表 | 方法 | 語法示例 | Python版本 | 優點 | 缺點 | | -------------- | -------------------- | -------- | ----------- | --------- | | f-string | `f"{a}你好{b}"` | 3.6+ | 簡潔、可運算、可讀性高 | 需新版Python | | `%` 格式化 | `"%s%s" % (a,b)` | 2.x~3.x | 相容舊代碼 | 可讀性較差 | | `str.format()` | `"{}{}".format(a,b)` | 2.6+ | 彈性高 | 稍顯冗長 | | 字串相加 | `a + b` | 通用 | 簡單直接 | 需轉型、易錯 | | print 多參數 | `print(a,b)` | 通用 | 不需轉型 | 控制力低 | --- 是否希望我幫你整理成一張簡潔的 **筆記圖表(含範例與差異)**?可用於學習筆記或簡報。 ## 運算符號 | 類型 | 運算符號 | 說明 | |--------|----------------------------|----------------------------------| | 算術 | + - * / // % ** | 加、減、乘、除、整除、餘數、次方 | | 比較 | == != > < >= <= | 相等、不等、大於、小於、等於 | | 邏輯 | and or not | 且、或、非 | | 指派 | = += -= *= ... | 複合賦值 | | 身份 | is, is not | 比較是否同一物件(記憶體) | | 包含 | in, not in | 判斷是否在某容器內 | ```python= fruits = ["蘋果", "香蕉"] print("蘋果" in fruits) # True print("葡萄" not in fruits) # True ``` ### 額外補充:資料型別判斷與轉換 ```python= x = "123" print(type(x)) # <class 'str'> print(type(int(x))) # <class 'int'> ``` ## 變數 ```python= x = 10 # 整數 int y = 3.14 # 浮點數 float name = "Amy" # 字串 str is_ok = True # 布林 bool(True/False) ``` ### 變數類型轉換 | 用法 | 範例 | 結果 | |--------------|--------------------------|-------------| | 整數 | int(變數) | int("123") → 123 | | 浮點數 | float(變數) | float("3.14") → 3.14 | | 字串 | str(變數) | str(123) → "123" | | 布林 | bool(變數) | bool(0) → False | ## 判斷式 ### if / elif / else ```python= score = 85 if score >= 90: print("優秀") elif score >= 60: print("及格") else: print("不及格") ``` ## List(串列) ```python= fruits = ["蘋果", "香蕉", "葡萄"] print(fruits[0]) # 蘋果 fruits.append("芒果") # 加入新水果 print(len(fruits)) # 長度(幾個元素) ``` | 操作 | 範例 | | ------------ | -------------------------------------------- | | 加入元素(尾端) | `fruits.append("kiwi")` | | 插入元素(指定位置) | `fruits.insert(1, "lemon")` | | 移除指定元素(第一個) | `fruits.remove("apple")` | | 彈出元素(預設最後一個) | `fruits.pop()` 或 `fruits.pop(1)` | | 清空 | `fruits.clear()` | | 計算長度 | `len(fruits)` | | 統計某值出現次數 | `fruits.count("banana")` | | 找到值第一次出現的位置 | `fruits.index("cherry")` | | 反轉順序 | `fruits.reverse()` | | 排序(由小到大) | `fruits.sort()`(需同類型元素) | | 排序(不改原 list) | `sorted(fruits)` | | 合併兩個 list | `fruits + ["orange", "watermelon"]` | | 複製 list | `copy = fruits.copy()` or `copy = fruits[:]` | ### sum()、min()、max() 快速求值 ```python= nums = [1, 2, 3] print(sum(nums)) # 6 print(min(nums)) # 1 print(max(nums)) # 3 ``` ## 字典 map ```python= person = { "name": "小明", "age": 18, "is_student": True } ``` ### 常用操作 ✅ 取值(透過 key) ```python= print(person["name"]) # 小明 ``` ✅ 使用 .get() 取值(推薦,防錯) ```python= print(person.get("age")) # 18 print(person.get("gender", "未知")) # 若 key 不存在,回傳預設值 ``` ✅ 修改 / 新增鍵值 ```python= person["age"] = 19 # 修改 person["gender"] = "男" # 新增 ``` ✅ 刪除鍵值 ```python= del person["is_student"] ``` | 方法 | 說明 | |--------------------|----------------------------------| | dict.keys() | 回傳所有 key(鍵) | | dict.values() | 回傳所有 value(值) | | dict.items() | 回傳所有 (key, value) 組 | | key in dict | 判斷是否有某個 key | | dict.clear() | 清空整個字典 | | dict.pop(key) | 移除指定 key 並回傳值(若無則錯誤) | | dict.update() | 合併另一個字典 | ### 判斷式運用 ```python= def handle_A(): print("優秀") def handle_B(): print("良好") def handle_C(): print("普通") actions = { "A": handle_A, "B": handle_B, "C": handle_C } grade = "B" actions.get(grade, lambda: print("未知"))() ``` 在這段程式碼中,主要使用了字典(`dict`)來儲存資料。以下是程式碼中出現的字典相關的操作解析,並將其整理成字典用法大全: 1. **創建字典** ```python a = {} ``` 使用大括號 `{}` 來創建一個空字典。 2. **將項目添加到字典** ```python a[i+1] = lst[i].strip() ``` 通過指定鍵值對(`a[i+1] = lst[i].strip()`)將值添加到字典中。這裡,`i+1` 是字典的鍵,`lst[i].strip()` 是值。`.strip()` 方法用於去除字符串的首尾空白字符。 3. **檢查字典中是否存在某個鍵** ```python if item in a.keys(): ``` 使用 `in` 操作符來檢查某個元素是否存在於字典的鍵(`a.keys()`)中。 4. **通過鍵訪問字典的值** ```python print(f"已存在: {a[item]}") ``` 使用 `a[item]` 來通過鍵 `item` 訪問字典中的值。 5. **向字典添加新項目** ```python a[item] = it ``` 這行代碼會把 `item` 作為鍵,`it` 作為值,將這個鍵值對添加到字典 `a` 中。 6. **將字典寫入檔案** ```python fw.write(f"{item}:{a[item]}\n") ``` 使用 `fw.write()` 來將字典的鍵值對寫入文件中。`f"{item}:{a[item]}"` 是格式化字串,將鍵和對應的值以 `: ` 分隔並寫入文件。 ### 字典常用操作總結 1. **創建字典**: ```python a = {} # 空字典 ``` 2. **檢查鍵是否存在**: ```python if key in a: # 檢查字典是否有該鍵 ``` 3. **訪問字典中的值**: ```python value = a[key] # 通過鍵訪問值 ``` 4. **向字典添加項目**: ```python a[key] = value # 添加鍵值對 ``` 5. **更新字典中的值**: ```python a[key] = new_value # 更新指定鍵的值 ``` 6. **遍歷字典**: ```python for key, value in a.items(): print(key, value) ``` 7. **刪除字典中的項目**: ```python del a[key] # 根據鍵刪除項目 ``` 8. **獲取所有鍵或值**: ```python keys = a.keys() # 返回字典的所有鍵 values = a.values() # 返回字典的所有值 ``` ## for迴圈 ### 基本語法 ```python= for 變數 in 可迭代物件: 執行的程式碼 ``` ### range() 搭配 for 迴圈 ```python= for i in range(5): print("目前 i 的值是:", i) ``` 📌 range(5) 會產生:0, 1, 2, 3, 4 ### 走訪 list(串列) ```python= fruits = ["蘋果", "香蕉", "葡萄"] for fruit in fruits: print("我喜歡吃", fruit) ``` ### 用 range(開始, 結束, 間隔) 來走訪數字 ```python= for num in range(1, 10, 2): print(num) ``` 📌 這會印出:1, 3, 5, 7, 9 ### 走訪字串中的每個字元 ```python= for char in "Hello": print(char) ``` ### 同時取出「索引值」和「內容」→ 使用 enumerate() ```python= colors = ["紅", "綠", "藍"] for i, color in enumerate(colors): print(f"第 {i} 個顏色是 {color}") ``` 🧠 補充:巢狀 for 迴圈(for 迴圈裡面又有 for) ```python= for i in range(1, 4): for j in range(1, 4): print(f"i = {i}, j = {j}") ``` ## while 迴圈 ```python= x = 0 while x < 5: print(x) x += 1 ``` 非常好 💪 在 Python 考試中,「**各類迴圈(loop)**」是最常考的基礎重點之一。 下面是我幫你整理的 —— ✅ **Python 各類迴圈使用大全**(含語法、用途、範例、差異與常見考點) --- # 🌀 Python 各類迴圈整理 Python 中常用的迴圈主要有: 1️⃣ `for` 迴圈 2️⃣ `while` 迴圈 3️⃣ `break`、`continue`、`else` 的搭配使用 4️⃣ `range()` 的應用 5️⃣ 巢狀迴圈(nested loop) --- ## 1️⃣ for 迴圈(for loop) **用途:** 重複執行「可迭代物件(iterable)」中的每個元素,例如 list、tuple、str、dict、range。 **語法:** ```python for 變數 in 可迭代物件: 執行的程式區塊 ``` **範例:** ```python # 逐一輸出清單中的項目 fruits = ["apple", "banana", "cherry"] for f in fruits: print(f) ``` **配合 range() 使用:** ```python for i in range(5): # 0,1,2,3,4 print(i) ``` **常見變形:** ```python for i in range(2, 10, 2): # 起始值2、終止值10(不含)、步長2 print(i) # 2, 4, 6, 8 ``` --- ## 2️⃣ while 迴圈(while loop) **用途:** 在條件為 `True` 時重複執行。 **語法:** ```python while 條件判斷式: 執行的程式區塊 ``` **範例:** ```python i = 1 while i <= 5: print("目前 i =", i) i += 1 ``` **無限迴圈(常考陷阱)** ```python while True: cmd = input("輸入 exit 離開:") if cmd == "exit": break ``` --- ## 3️⃣ break、continue、else 的使用 ### 🔹 `break`:強制跳出整個迴圈 ```python for i in range(10): if i == 5: break print(i) # 輸出:0 1 2 3 4 ``` ### 🔹 `continue`:跳過本次迴圈,直接進入下一輪 ```python for i in range(5): if i == 2: continue print(i) # 輸出:0 1 3 4 ``` ### 🔹 `else`:當迴圈「正常結束」時執行(沒有被 break 中斷) ```python for i in range(5): print(i) else: print("for 正常結束") # 若中途 break,else 不執行 for i in range(5): if i == 3: break print(i) else: print("不會執行這裡") ``` --- ## 4️⃣ range() 函式 **語法:** ```python range(起始, 終止, 步長) ``` | 參數 | 意義 | 範例 | | -- | ---------- | ----------------------------- | | 起始 | 起始值(預設 0) | range(5) → 0~4 | | 終止 | 終止值(不包含) | range(2, 6) → 2,3,4,5 | | 步長 | 每次遞增或遞減的幅度 | range(10, 0, -2) → 10,8,6,4,2 | **搭配 for:** ```python for i in range(3, 10, 2): print(i) # 3,5,7,9 ``` --- ## 5️⃣ 巢狀迴圈(Nested Loop) **用途:** 一個迴圈裡面再放另一個迴圈,常用於輸出矩陣或組合。 **範例:** ```python for i in range(1, 4): for j in range(1, 4): print(i, j) ``` **輸出:** ``` 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 ``` **九九乘法表範例:** ```python for i in range(1, 10): for j in range(1, 10): print(f"{i}x{j}={i*j}", end="\t") print() ``` --- ## 6️⃣ 搭配 enumerate() 與 zip()(進階常考) ### 🔹 enumerate():同時取得索引與值 ```python fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(index, fruit) # 0 apple # 1 banana # 2 cherry ``` ### 🔹 zip():同時迭代多個序列 ```python names = ["Amy", "Bob", "Cat"] scores = [85, 90, 78] for n, s in zip(names, scores): print(f"{n} 的分數是 {s}") ``` --- ## 7️⃣ 綜合應用範例 ### ✅ for + if ```python for i in range(10): if i % 2 == 0: print(f"{i} 是偶數") ``` ### ✅ while + break ```python count = 0 while True: if count == 5: break print("count =", count) count += 1 ``` ### ✅ 巢狀 + 判斷 ```python for i in range(1, 4): for j in range(1, 4): if i == j: print(f"i=j={i}") ``` --- ## 8️⃣ for 與 while 的差異比較表 | 特點 | for 迴圈 | while 迴圈 | | -------- | -------------- | ----------- | | 適用情境 | 已知執行次數 | 未知次數(依條件控制) | | 結束條件 | range 或可迭代物件結束 | 條件判斷為 False | | 常見用途 | 清單、字串、range | 用戶輸入、重複試驗 | | 是否可能無限迴圈 | ❌(除非 range 設錯) | ✅ 需注意條件控制 | 是否希望我幫你做成一份 📘「**Python 迴圈考前懶人筆記**」Markdown 或 PDF 版? 可以直接列印或放進手機複習。 ## 函式 ```python= def greet(name): print("你好," + name) greet("小明") ``` 📌 def 用來定義函式,括號中是參數,greet("小明") 是呼叫函式。 ### 回傳值類型 不像 C++ 那樣要指定型態(Python 是動態型別) ```python= def add(a, b): return a + b result = add(3, 4) print(result) # 7 ``` 📌 雖然不需要指定型別,但你可以「標註」型態(可選): ```python= def add(a: int, b: int) -> int: return a + b ``` 非常好 💪 `def`(定義函式)是 Python 中非常核心、也常出現在考試的章節之一。 以下是我幫你整理的—— # 🧩 Python 函式(def)使用大全 ## 一、基本概念 在 Python 中,**函式(function)** 是一段可重複使用的程式碼, 用來執行特定任務、回傳結果、讓程式更簡潔與模組化。 --- ## 二、基本語法 ```python def 函式名稱(參數1, 參數2, ...): """(選擇性)函式說明文字 docstring""" 程式區塊 return 回傳值 ``` **範例:** ```python def say_hello(name): print(f"哈囉,{name}!") say_hello("小明") ``` 📤 輸出: ``` 哈囉,小明! ``` --- ## 三、`return` 回傳值 * `return` 用於**回傳函式的結果**。 * 若沒有 `return`,預設回傳 `None`。 ```python def add(a, b): return a + b result = add(3, 5) print(result) # 8 ``` 若沒有回傳值: ```python def show(): print("這只是輸出,不回傳") x = show() print(x) # None ``` --- ## 四、參數的種類與使用 ### 1️⃣ **位置參數(positional arguments)** 依傳入順序對應。 ```python def greet(name, age): print(f"{name} 今年 {age} 歲") greet("小明", 18) ``` --- ### 2️⃣ **預設參數(default arguments)** 給參數設定預設值,可省略。 ```python def greet(name="小明"): print(f"哈囉,{name}") greet() # 哈囉,小明 greet("小美") # 哈囉,小美 ``` --- ### 3️⃣ **關鍵字參數(keyword arguments)** 用「名稱 = 值」指定參數。 ```python def student(name, age): print(f"{name} - {age}") student(age=18, name="小美") ``` --- ### 4️⃣ **不定參數(*args, **kwargs)** #### 🔹 `*args`:接收多個位置參數(變長參數) ```python def add_all(*nums): total = sum(nums) print(total) add_all(1, 2, 3, 4) # 10 ``` #### 🔹 `**kwargs`:接收多個關鍵字參數 ```python def show_info(**info): for k, v in info.items(): print(k, ":", v) show_info(name="小明", age=18, city="台北") ``` --- ## 五、函式的回傳多個值 可一次回傳多個值(以 tuple 型態)。 ```python def get_info(): return "小明", 18 name, age = get_info() print(name, age) ``` --- ## 六、函式內外變數(作用域 Scope) | 類型 | 範例 | 說明 | | ---- | -------- | ------------ | | 區域變數 | 函式內宣告的變數 | 只能在函式內使用 | | 全域變數 | 在函式外宣告 | 任何地方可用(若未遮蔽) | ```python x = 10 # 全域變數 def func(): x = 5 # 區域變數 print("函式內 x =", x) func() print("函式外 x =", x) ``` 📤 輸出: ``` 函式內 x = 5 函式外 x = 10 ``` --- ### 🔹 使用 `global` 修改全域變數 ```python count = 0 def add(): global count count += 1 add() print(count) # 1 ``` --- ## 七、lambda(匿名函式) 簡化版函式(只有一行運算式),常與 `map()`、`filter()`、`sorted()` 搭配。 ```python square = lambda x: x**2 print(square(5)) # 25 ``` **搭配使用範例:** ```python nums = [1, 2, 3, 4] squared = list(map(lambda x: x**2, nums)) print(squared) # [1, 4, 9, 16] ``` --- ## 八、函式中的文件字串(docstring) 用三引號 `""" """` 撰寫說明,可用 `help()` 查看。 ```python def add(a, b): """這個函式會回傳 a 與 b 的總和""" return a + b help(add) ``` --- ## 九、巢狀函式(Nested Function) 函式裡面再定義函式(常用於封裝或閉包)。 ```python def outer(): def inner(): print("這是內部函式") inner() outer() ``` --- ## 🔟 常見考題方向 🔥 | 題型 | 重點 | 範例 | | -------------- | ------------- | --------------------------- | | 定義與呼叫函式 | 語法正確性 | `def func(x): return x+1` | | return 用法 | 函式是否有回傳值 | `print(func()) vs x=func()` | | 參數類型 | 預設值、關鍵字、*args | 考參數順序與錯誤訊息 | | global / local | 區域變數遮蔽全域 | `x` 的最終值? | | lambda | 匿名函式簡寫 | `lambda x:x*2` | | 多重回傳 | 回傳 tuple 解包 | `a,b=func()` | --- ## ✅ 考試重點速記表 | 功能 | 關鍵字 | 範例 | | ------ | ------------------- | --------------------- | | 定義函式 | `def` | `def f(): ...` | | 回傳結果 | `return` | `return x+y` | | 不定參數 | `*args`, `**kwargs` | `def f(*x, **y): ...` | | 匿名函式 | `lambda` | `lambda x:x+1` | | 修改全域變數 | `global` | `global a` | | 文件說明 | `"""doc"""` | `help(func)` | 當然可以 👇 這是 **Python 處理 `.txt` 檔案(文字檔)輸入輸出** 的完整詳細筆記,適合考試或實作時快速查閱。 # 📝 Python TXT 檔案輸入輸出筆記 ## 一、開啟與關閉檔案 ### 📌 基本語法 ```python f = open("檔名.txt", "模式", encoding="utf-8") # ...操作... f.close() ``` ### 📌 模式(mode)說明: | 模式 | 意義 | 說明 | | --------------- | ----- | ------------ | | `'r'` | 讀取 | 若檔案不存在會報錯 | | `'w'` | 寫入 | 若檔案存在會覆蓋原內容 | | `'a'` | 附加 | 在原檔案最後繼續寫入 | | `'r+'` | 讀寫 | 可同時讀寫,不覆蓋 | | `'w+'` | 讀寫 | 若檔案存在會清空再寫 | | `'a+'` | 讀寫 | 可讀取也可在最後附加 | | `'rb'` / `'wb'` | 二進位模式 | 適用非文字檔案(如圖片) | --- ## 二、文字檔讀取(input) ### 1️⃣ 讀取整個檔案內容 ```python f = open("data.txt", "r", encoding="utf-8") content = f.read() print(content) f.close() ``` > `read()` → 一次讀完整個檔案,回傳字串。 --- ### 2️⃣ 逐行讀取 ```python f = open("data.txt", "r", encoding="utf-8") for line in f: print(line.strip()) # strip() 去除換行符號 f.close() ``` > 適合處理大量資料。 --- ### 3️⃣ 讀成列表 ```python f = open("data.txt", "r", encoding="utf-8") #"C:\\Users\\user\\Desktop\\data.txt" lines = f.readlines() # 每一行是一個元素 # int的list # listy = list(map(int, f.readlines())) print(lines) f.close() ``` > `readlines()` 回傳 list,例如: > `["apple\n", "banana\n", "cherry\n"]` --- ## 三、文字檔寫入(output) ### 1️⃣ 覆蓋寫入 ```python f = open("output.txt", "w", encoding="utf-8") f.write("Hello World!\n") f.write("第二行文字") f.close() ``` > 若檔案已存在 → 清空後重寫。 --- ### 2️⃣ 附加寫入 ```python f = open("output.txt", "a", encoding="utf-8") f.write("新增一行\n") f.close() ``` > 不會覆蓋原內容。 --- ### 3️⃣ 同時寫入多行 ```python f = open("data.txt", "w", encoding="utf-8") data = ["Apple\n", "Banana\n", "Cherry\n"] f.writelines(data) f.close() ``` > `writelines()` 會照順序寫入 list 中的每個字串。 --- ## 四、with 語法(推薦) ### ✅ 自動關閉檔案 ```python with open("data.txt", "r", encoding="utf-8") as f: for line in f: print(line.strip()) ``` > 不需 `f.close()`,程式離開區塊時會自動關閉。 --- ## 五、範例:讀取 + 查詢 + 新增資料 ```python file_path = "data.txt" # 讀取全部 with open(file_path, "r", encoding="utf-8") as fr: lines = fr.read().splitlines() # 查詢 item = input("請輸入要查詢的項目:") if item in lines: print("找到資料:", item) else: print("未找到,已新增!") with open(file_path, "a", encoding="utf-8") as fw: fw.write(item + "\n") ``` --- ## 六、其他實用函式與技巧 | 函式 | 功能 | | ----------------------- | ------------------ | | `tell()` | 回傳目前檔案指標位置(byte 數) | | `seek(offset)` | 移動檔案指標位置 | | `truncate(size)` | 截斷檔案到指定大小 | | `os.path.exists("檔案名")` | 檢查檔案是否存在 | | `os.remove("檔案名")` | 刪除檔案 | --- ## 七、錯誤處理(例外狀況) ```python try: f = open("abc.txt", "r", encoding="utf-8") print(f.read()) except FileNotFoundError: print("找不到檔案!") finally: f.close() ``` --- ## 八、常見考題重點 ⚡ ✅ 檔案模式 `'r'`, `'w'`, `'a'` 差別 ✅ `read()` vs `readlines()` ✅ 使用 `with open()` 範例 ✅ 寫入新資料不覆蓋的方法 ✅ 如何去除換行符號 `strip()` ✅ 若檔案不存在時會報錯的是哪一種模式?(→ `'r'`) # 🧾 Python 判斷檔案是否存在 — 全面筆記 ## ✅ 一、使用 `os.path` 模組(最傳統、最常用) ### 📌 1️⃣ 判斷檔案是否存在 ```python import os if os.path.isfile("data.txt"): print("✅ 檔案存在!") else: print("❌ 檔案不存在!") ``` | 函式 | 用途 | | ---------------------- | ---------- | | `os.path.exists(path)` | 檔案或資料夾是否存在 | | `os.path.isfile(path)` | **是否為檔案** | | `os.path.isdir(path)` | **是否為資料夾** | 📘 範例: ```python path = "C:\\Users\\user\\Desktop\\test.txt" if os.path.exists(path): print("存在(可能是檔案或資料夾)") if os.path.isfile(path): print("是檔案") if os.path.isdir(path): print("是資料夾") ``` --- ## ✅ 二、使用 `pathlib` 模組(Python 3.4+ 現代寫法) ```python from pathlib import Path file = Path("data.txt") if file.exists(): print("檔案存在") else: print("檔案不存在") ``` ### 📦 常用屬性與方法: | 方法 | 說明 | | ----------------------------------------- | -------------- | | `Path.exists()` | 是否存在 | | `Path.is_file()` | 是否為檔案 | | `Path.is_dir()` | 是否為資料夾 | | `Path.name` | 檔名(含副檔名) | | `Path.stem` | 檔名(不含副檔名) | | `Path.suffix` | 副檔名(例如 `.txt`) | | `Path.parent` | 上層路徑 | | `Path.mkdir(parents=True, exist_ok=True)` | 建立資料夾 | | `Path.unlink()` | 刪除檔案 | 📘 範例: ```python from pathlib import Path f = Path("C:/Users/user/Desktop/py/1016.txt") if not f.exists(): print("檔案不存在,建立新檔案!") f.write_text("Hello\n", encoding="utf-8") else: print("檔案已存在!") ``` --- ## ✅ 三、例外處理法(try + except) ```python try: with open("data.txt", "r", encoding="utf-8") as f: print(f.read()) except FileNotFoundError: print("找不到檔案!") ``` > 🚨 適合在不確定檔案存在時直接處理錯誤。 > 不需要先用 `os.path` 判斷,直接測開啟是否會報錯。 --- ## ✅ 四、結合自動建立檔案與資料夾的範例 ```python import os folder = "C:\\Users\\user\\Desktop\\py" file_path = os.path.join(folder, "1016.txt") # 檢查資料夾 if not os.path.isdir(folder): os.makedirs(folder) print("✅ 已建立資料夾") # 檢查檔案 if not os.path.isfile(file_path): with open(file_path, "w", encoding="utf-8") as f: f.write("初始內容\n") print("✅ 檔案已建立") else: print("📂 檔案已存在") ``` --- ## ✅ 五、搭配刪除檔案與其他檔案操作 | 函式 | 功能 | | ----------------------------- | ----------- | | `os.remove("file.txt")` | 刪除檔案 | | `os.rename("a.txt", "b.txt")` | 檔案改名 | | `os.path.getsize("a.txt")` | 檔案大小(bytes) | | `os.listdir("資料夾")` | 列出所有檔案 | | `os.getcwd()` | 取得目前工作目錄 | | `os.chdir("路徑")` | 改變工作目錄 | --- ## ✅ 六、最推薦實用範例(結合 all-in-one) ```python import os file_path = "C:\\Users\\user\\Desktop\\py\\1016.txt" # 1. 判斷資料夾 folder = os.path.dirname(file_path) if not os.path.isdir(folder): os.makedirs(folder) print("✅ 已建立資料夾") # 2. 判斷檔案 if not os.path.isfile(file_path): with open(file_path, "w", encoding="utf-8") as f: f.write("Hello Python\n") print("✅ 檔案已建立") else: print("📁 檔案已存在") ``` --- ## ✅ 七、考試重點 ⚡️ | 題目方向 | 答案重點 | | --------------- | ----------------------------------------- | | 判斷檔案是否存在 | `os.path.isfile()` 或 `Path.exists()` | | 判斷資料夾是否存在 | `os.path.isdir()` 或 `Path.is_dir()` | | 若檔案不存在則建立 | `if not os.path.exists(): open(..., 'w')` | | try-except 錯誤處理 | `FileNotFoundError` | | 現代寫法 | `from pathlib import Path` | # 🐍 Python Matplotlib 圖表語法大全 中文: plt.rcParams["font.sans-serif"] ="Microsoft JhengHei" ```python import matplotlib.pyplot as plt ``` --- ### 📈 一、基本繪圖 | 語法 | 說明 | 範例 | | --------------------------------------------------- | ------ | -------------------------------------------------------------- | | `plt.plot(x, y)` | 繪製折線圖 | `plt.plot([1,2,3],[4,5,6])` | | `plt.scatter(x, y)` | 繪製散點圖 | `plt.scatter(x, y, color='r')` | | `plt.bar(x, y)` | 長條圖(直) | `plt.bar(['A','B'], [5,3])` | | `plt.barh(x, y)` | 長條圖(橫) | `plt.barh(['A','B'], [5,3])` | | `plt.pie(values, labels=labels, autopct='%1.1f%%')` | 圓餅圖 | `plt.pie([30,50,20], labels=['A','B','C'], autopct='%1.1f%%')` | | `plt.hist(data, bins=10)` | 直方圖 | `plt.hist(數列, bins=10, color='g')` | --- ### 🎨 二、`plt.plot()` 主要屬性與樣式 | 屬性 | 意義 | 範例 | | --------------------------------- | -------------- | -------------- | | `'b' 'g' 'r' 'c' 'm' 'y' 'k' 'w'` | 顏色代碼(藍、綠、紅...) | `'r'` → 紅色 | | `'-' '--' '-.' ':'` | 線條樣式 | `'--'` → 虛線 | | `'o' 's' '^' '*' 'x' 'D'` | 點形狀 | `'s'` → 方形 | | `label='名稱'` | 圖例名稱 | `label='anna'` | | `linewidth=2` | 線條粗細 | | | `markersize=8` | 點大小 | | | `markerfacecolor='y'` | 點內顏色 | | | `markeredgecolor='k'` | 點邊顏色 | | ✅ **綜合例:** ```python plt.plot(x, y, 'b-s', label='anna', linewidth=2, markersize=8) ``` (藍線、方形標記、線寬2、名稱anna) --- ### 🧭 三、標題與標籤 | 語法 | 說明 | | ------------------------ | ---------- | | `plt.title('主標題')` | 設定圖表標題 | | `plt.xlabel('X軸名稱')` | 設定 X 軸標籤 | | `plt.ylabel('Y軸名稱')` | 設定 Y 軸標籤 | | `plt.suptitle('整張圖大標題')` | 整體標題(多子圖時) | --- ### 📏 四、座標軸設定 | 語法 | 說明 | | ------------------------------------------------------- | -------- | | `plt.xlim(min, max)` | 限制 X 軸範圍 | | `plt.ylim(min, max)` | 限制 Y 軸範圍 | | `plt.xticks(list)` | 設定 X 軸刻度 | | `plt.yticks(list)` | 設定 Y 軸刻度 | | `plt.axis([xmin, xmax, ymin, ymax])` | 同時設定範圍 | | `plt.grid(True)` | 顯示格線 | | `plt.grid(color='gray', linestyle='--', linewidth=0.5)` | 格線樣式 | --- ### 🧩 五、圖例(Legend) | 語法 | 說明 | | -------------------------------------------------------------------------------------------------- | ------ | | `plt.legend()` | 顯示圖例 | | `plt.legend(loc='upper right')` | 設定位置 | | `plt.legend(fontsize=12)` | 設定字體大小 | | `plt.legend(title='圖例名稱')` | 加上圖例標題 | | 🔸`loc` 可選值:`'best'`, `'upper left'`, `'upper right'`, `'lower left'`, `'lower right'`, `'center'` | | --- ### 🔢 六、文字與標記 | 語法 | 說明 | | -------------------------------------------------------------------------------- | --------- | | `plt.text(x, y, '文字')` | 在指定位置顯示文字 | | `plt.annotate('文字', xy=(x,y), xytext=(x2,y2), arrowprops=dict(arrowstyle='->'))` | 加箭頭註解 | --- ### 📊 七、子圖(多張圖) | 語法 | 說明 | | --------------------------------- | ----------- | | `plt.subplot(行數, 列數, 編號)` | 建立多子圖(同一視窗) | | `plt.figure(figsize=(寬,高))` | 設定整張圖大小 | | `plt.tight_layout()` | 自動調整子圖間距 | | 例:`plt.subplot(2,1,1)` → 第1列第1個子圖 | | --- ### 💾 八、輸出與顯示 | 語法 | 說明 | | ----------------------- | ------------ | | `plt.show()` | 顯示圖表(一定要放最後) | | `plt.savefig('圖名.png')` | 儲存圖片 | | `plt.close()` | 關閉圖表視窗 | --- ### 🧠 九、實戰範例 ```python import matplotlib.pyplot as plt x = [1,2,3,4,5] y1 = [2,4,6,8,10] y2 = [1,3,5,7,9] plt.figure(figsize=(6,4)) # 設定大小 plt.plot(x, y1, 'b-o', label='A') # 第一條線 plt.plot(x, y2, 'r--s', label='B') # 第二條線 plt.title("成績比較") plt.xlabel("次數") plt.ylabel("分數") plt.xlim(0,6) plt.ylim(0,12) plt.grid(True, linestyle='--', alpha=0.5) plt.legend(loc='upper left') plt.show() ``` --- ### ⚙️ 十、進階補充(考加分) | 功能 | 語法 | | ------ | -------------------------------------------------------- | | 多個圖放一起 | `plt.subplot(2,2,1)` | | 多組圖疊加 | 多次 `plt.plot()` | | 設字型大小 | `plt.rcParams['font.size']=12` | | 中文顯示 | `plt.rcParams['font.sans-serif']=['Microsoft JhengHei']` | | 儲存透明背景 | `plt.savefig('圖.png', transparent=True)` | 非常棒 👏 你現在已經在寫出完整的爬蟲程式了,下面這份筆記我幫你整理成「**Python爬蟲考試全攻略**」📘, 內容包含:核心概念、語法大全、BeautifulSoup 選取方法、常見錯誤、實戰範例、延伸模組。