前言|Preface
這本電子書專為「零基礎到進階」學習者而設,透過循序漸進的章節, 協助你建立紮實的 Python 程式設計能力。
This eBook is designed for learners who want to go from absolute beginner to advanced Python developer, step by step, with solid foundations and practical skills.
第 1 章|Python 是甚麼?
Python 是一種高階、直譯式、跨平台的程式語言,以可讀性高及生態系統龐大而聞名。
Python is a high-level, interpreted, cross-platform programming language known for its readability and massive ecosystem.
Python 的常見用途
- 網站後端(Django / Flask / FastAPI)
- 數據分析與 AI(NumPy / Pandas / PyTorch)
- 自動化與腳本(Automation / Scripting)
第 2 章|安裝與環境設定 Setup
建議初學者使用官方 Python 以及 VS Code (Visual Studio Code) 作為開發環境,這是目前業界最主流的組合。
1. 安裝 Python
前往 python.org 下載最新版本。
Crucial: Make sure to check "Add Python to PATH" during installation.
2. 設定 VS Code 開發環境
安裝完 VS Code 後,請在「擴充功能 (Extensions)」搜尋並安裝以下插件:
- Python (by Microsoft): 提供語法提示、偵錯功能。
- Pylance: 讓程式碼補全更聰明。
Install the "Python" extension in VS Code for linting and debugging.
3. 驗證安裝結果
開啟終端機(Terminal),輸入以下指令確認:
# 檢查 Python 版本
python --version
# 進入 Python 互動模式 (輸入 exit() 退出)
python
4. 進階:建立虛擬環境 (Virtual Environments)
專家習慣為每個專案建立獨立的虛擬環境,避免不同專案的套件互相衝突。
# 建立名為 .venv 的環境
python -m venv .venv
# 啟動環境 (Windows)
.venv\Scripts\activate
# 啟動環境 (Mac/Linux)
source .venv/bin/activate
Virtual environments keep your projects organized and prevent library conflicts.
第 3 章|基礎語法 Fundamentals
1. 變數與動態型別 (Dynamic Typing)
Python 不需要事先宣告資料型別(如 int 或 string),它會根據你賦予的值自動判斷。
# 賦值即建立變數
name = "Alice" # 字串 (str)
age = 18 # 整數 (int)
height = 160.5 # 浮點數 (float)
is_student = True # 布林值 (bool)
# 你甚至可以改變變數的型別(但不建議這樣做)
x = 10
x = "Now I am a string"
Variables in Python do not require explicit type declaration; the type is inferred at runtime.
2. 常見資料型別一覽
| 型別名稱 | 關鍵字 | 範例 |
|---|---|---|
| 字串 | str |
"Hello", 'Python' |
| 整數 | int |
-5, 100 |
| 浮點數 | float |
3.14, 2.0 |
| 布林值 | bool |
True, False |
3. 變數命名規範 (Naming Rules)
遵循 Pythonic 的命名風格能讓你的程式碼更專業:
- 蛇形命名法 (snake_case): 變數名請用小寫,並用底線分隔單字,例如
user_name。 - 不能以數字開頭: 例如
1st_user是錯誤的。 - 大小寫敏感:
Age與age是不同的變數。
Follow snake_case for variable names and avoid starting with numbers.
4. 檢查型別與輸出
你可以使用 type() 函式來確認變數的型別,並使用 f-string 進行格式化輸出。
# 檢查型別
print(type(height)) # Output: <class 'float'>
# 格式化輸出 (f-string)
print(f"{name} is {age} years old.")
# Output: Alice is 18 years old.
Use type() to check data types and f-strings for convenient string formatting.
第 4 章|流程控制 Control Flow
程式不再只是由上而下執行,透過流程控制,我們可以讓程式根據不同條件走不同的路。
1. 條件判斷 if / elif / else
當你有超過兩個以上的條件時,請使用 elif (else if)。
score = 85
if score >= 90:
print("Excellent")
elif score >= 60:
print("Pass")
else:
print("Fail")
and, or, not 來組合條件。例如:
if score > 60 and score < 80:
2. 迴圈 Loops
Python 主要有兩種迴圈:for 用於已知次數或遍歷對象,while 用於條件成立時持續執行。
A. For 迴圈與 Range
range(start, stop, step) 是一個非常強大的工具。
# 印出 0 到 4
for i in range(5):
print(i)
# 從 1 開始到 10,每次跳 2 步 (印出 1, 3, 5, 7, 9)
for i in range(1, 10, 2):
print(i)
B. While 迴圈
只要條件為真,就會一直執行。請務必確保條件有結束的一天,否則會造成「死迴圈」。
count = 0
while count < 3:
print(f"Count is {count}")
count += 1 # 記得更新條件
3. 迴圈控制:break 與 continue
- break: 直接強制跳出整個迴圈。
- continue: 跳過本次剩下的程式碼,直接進入下一次迴圈。
for i in range(10):
if i == 3:
continue # 跳過 3
if i == 5:
break # 看到 5 就結束整個迴圈
print(i)
Control flow allows your program to make decisions and repeat tasks efficiently.
第 5 章|函式 Functions
函式是將重複的邏輯封裝起來的工具,能讓程式碼更容易維護且清晰。
1. 基本定義與回傳
def greet(name):
return f"Hello, {name}!"
print(greet("Python"))
2. 預設參數與關鍵字參數
你可以為參數設定預設值,讓函式呼叫更具彈性。
def power(number, exp=2):
return number ** exp
print(power(5)) # 使用預設值: 25
print(power(5, 3)) # 覆蓋預設值: 125
3. 多個回傳值
Python 允許一個函式同時回傳多個結果,這在處理數據時非常方便。
def get_user_info():
name = "Bob"
age = 25
return name, age # 實際上回傳的是一個 Tuple
user_name, user_age = get_user_info()
print(f"Name: {user_name}, Age: {user_age}")
Functions allow code reuse, support default arguments, and can return multiple values.
第 5.1 章|核心資料結構 Data Structures
除了變數,Python 的列表(List)與字典(Dictionary)是處理大量資料的核心工具。
1. 列表 Lists (有序集合)
列表像是一排儲物櫃,每個櫃子都有編號(索引)。
fruits = ["Apple", "Banana", "Cherry", "Date"]
# 切片 (Slicing) - 獲取子列表 [開始:結束(不包含)]
print(fruits[1:3]) # Output: ["Banana", "Cherry"]
# 常用方法
fruits.append("Orange") # 在末尾新增
fruits.remove("Banana") # 刪除指定元素
length = len(fruits) # 獲取長度
2. 字典 Dictionaries (鍵值對)
字典透過「鍵 (Key)」來尋找「值 (Value)」,查詢速度極快。
student = {
"name": "Alice",
"age": 20,
"score": 95
}
# 獲取所有鍵或值
print(student.keys()) # dict_keys(['name', 'age', 'score'])
print(student.values()) # dict_values(['Alice', 20, 95])
# 安全讀取資料 (避免 KeyError)
grade = student.get("grade", "N/A") # 若無此鍵,回傳預設值 N/A
3. 元組與集合 (Tuples & Sets)
- Tuple (元組): 不可修改的列表,通常用於保護資料不被變更。
coords = (10, 20) - Set (集合): 不重複且無序的集合,常用於去除重複項。
unique_nums = {1, 2, 2, 3} # 結果為 {1, 2, 3}
Lists are ordered sequences; Dictionaries are key-value pairs. Tuples are immutable, and Sets store unique elements.
第 5.2 章|Pythonic Code 與最佳實踐
Pythonic Thinking & Best Practices
寫得「能跑」只是開始,寫得「像 Python 工程師」才是進階。
Pythonic code emphasizes readability, clarity, and intent.
1️⃣ List / Dict Comprehension
# ❌ 初學者寫法
squares = []
for i in range(10):
squares.append(i * i)
# ✅ Pythonic 寫法
squares = [i * i for i in range(10)]
2️⃣ enumerate 與 zip
names = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(names, start=1):
print(i, name)
names = ["Alice", "Bob"]
scores = [90, 85]
for name, score in zip(names, scores):
print(name, score)
3️⃣ Context Manager(with)
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
Explicit is better than implicit.
- 能使用 comprehension 重構 for-loop
- 理解 with 的用途
- 優先使用內建函式
第 5.3 章: 非同步程式設計 (AsyncIO)
在傳統的 Python 程式中,程式碼是「同步」執行的,這意味著如果一個任務在等待(例如下載大檔案),整個程式都會停下來。asyncio 允許我們在等待 I/O 時執行其他任務。
1. 基本語法:async 與 await
import asyncio
async def say_hello():
print("等待中...")
await asyncio.sleep(2) # 模擬耗時的 I/O 操作
print("你好,非同步世界!")
# 執行非同步進入點
if __name__ == "__main__":
asyncio.run(say_hello())
2. 同時執行多個任務 (Parallel Tasks)
使用 asyncio.gather 可以同時啟動多個協程,大幅節省時間。
import asyncio
import time
async def fetch_data(id, delay):
print(f"任務 {id} 開始...")
await asyncio.sleep(delay)
return f"任務 {id} 完成"
async def main():
start = time.perf_counter()
# 同時執行三個任務
results = await asyncio.gather(
fetch_data(1, 3),
fetch_data(2, 1),
fetch_data(3, 2)
)
end = time.perf_counter()
print(results)
print(f"總共花費時間: {end - start:.2f} 秒")
asyncio.run(main())
async 定義協程與 await 等待任務的區別。
第 6 章|進階主題 Advanced Topics
1. 物件導向 (OOP)
透過「類別 (Class)」來建立自己的物件藍圖。
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy")
print(my_dog.bark())
2. 例外處理 (Exception Handling)
避免程式因為錯誤而直接崩潰。
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
finally:
print("Execution finished.")
3. 模組與套件 (Modules)
使用 Python 豐富的標準函式庫。
import random
import datetime
print(random.randint(1, 10)) # 隨機產生 1-10 的數字
print(datetime.date.today()) # 印出今天日期
Understanding these concepts allows you to write more robust and modular code.
第 6.1 章|檔案與資料處理實戰
File I/O & Real-World Data Flow
真實世界的程式,99% 都在處理資料。
1️⃣ 讀寫文字檔
with open("notes.txt", "r", encoding="utf-8") as f:
print(f.read())
with open("log.txt", "a", encoding="utf-8") as f:
f.write("Program started\n")
2️⃣ JSON(API 世界標準)
import json
data = {"name": "Alice", "score": 95}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
with open("data.json", "r") as f:
obj = json.load(f)
print(obj["name"])
3️⃣ pathlib(現代寫法)
from pathlib import Path
path = Path("data") / "notes.txt"
if path.exists():
print(path.read_text())
- 能安全讀寫檔案
- 理解 JSON 與 dict 對應
- 使用 pathlib
第 6.2 章|測試、除錯與工程思維
Testing, Debugging & Engineering Mindset
1️⃣ 看懂 Traceback
從最後一行錯誤類型開始讀。
2️⃣ print Debug
print("DEBUG:", value)
3️⃣ 單元測試(pytest)
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
4️⃣ 工程師習慣
- 一個函式只做一件事
- 命名勝過註解
- 寫給未來的自己
- 能獨立除錯
- 理解測試價值
- 具備工程思維
第 7 章|專家之路 Becoming an Expert
掌握語法只是起點,真正的專家來自於解決問題的深度與廣度。
Mastering syntax is just the beginning. True expertise comes from the depth and breadth of your problem-solving skills.
1. 選定專業領域 (Choosing Your Domain)
不要試圖學習所有東西,先深耕一個方向:
- 數據科學 (Data Science): 學習 Pandas, NumPy, Matplotlib 與 Scikit-learn。
- 網頁開發 (Web Development): 掌握 Django 或 Flask 框架,並理解 RESTful API。
- 自動化與爬蟲 (Automation): 學習 Selenium, BeautifulSoups 與正則表達式 (Regex)。
Focus on one domain: Data Science, Web Dev, or Automation/Scripting.
2. 撰寫「工程級」代碼 (Writing Production-Ready Code)
專家與業餘者的區別在於程式碼的可維護性:
- 型別提示 (Type Hinting): 使用
def func(name: str) -> int:增加代碼健壯性。 - 單元測試 (Unit Testing): 學習使用
pytest確保程式邏輯正確。 - PEP 8 規範: 嚴格遵守 Python 官方風格指南,並使用
Black或Flake8自動格式化。
3. 深入底層原理 (Understanding the Internals)
理解 Python 是如何運作的,能幫你寫出效能更高的程式:
Deep dive into Memory Management, GIL, and Metaprogramming.
4. 貢獻與交流 (Contribution & Community)
閱讀知名的開源專案原始碼(如 requests),並嘗試在 GitHub 上貢獻。
參與實體社群(如 PyCon)能讓你接觸到最新的技術趨勢。
Read famous open-source code and contribute to the community via GitHub or PyCon.
🚀 給學習者的最後一句話
「最好的學習方式就是動手做,並在錯誤中尋找答案。」
"The best way to learn is to build something and find answers through your mistakes."
🧰 Python 常用函式庫介紹與應用
Python 最強大的地方在於其「內建電池」(Batteries Included) 的哲學,以及龐大的第三方生態系。
1. 標準函式庫 Standard Libraries (內建)
datetime|日期與時間
用途:處理時間戳記、記錄 Log 時間。
from datetime import datetime
now = datetime.now()
print(f"現在時間:{now.strftime('%Y-%m-%d %H:%M:%S')}")
os & json|檔案系統與資料格式
用途:自動化管理檔案、解析 API 回傳的 JSON 格式。
import os, json
# 檢查檔案是否存在
print(os.path.exists("test.py"))
# JSON 轉換為字典
data = '{"name": "Python", "type": "Language"}'
obj = json.loads(data)
print(obj["name"])
2. 第三方函式庫 Third-party Libraries (需安裝)
安裝指令:pip install requests pandas matplotlib beautifulsoup4
requests|網路請求與 API
用途:呼叫外部 API (如天氣、匯率) 或抓取網頁內容。
import requests
r = requests.get("https://api.github.com")
print(f"連線狀態:{r.status_code}") # 200 代表成功
pandas|資料分析神器
用途:操作 Excel、CSV 以及大數據分析。
import pandas as pd
df = pd.DataFrame({"Name": ["Alice", "Bob"], "Age": [25, 30]})
print(df)
matplotlib|資料視覺化
用途:將數據畫成折線圖、圓餅圖。
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 15])
plt.show() # 彈出圖表視窗
Mastering these libraries will transition you from a coder to a problem solver.
🤖 Python 與 AI 應用|AI & Machine Learning
Python 是進入人工智慧領域的通行證。從數據預測到生成式 AI,Python 都有強大的套件支援。
1. 機器學習基礎 (Machine Learning)
使用 scikit-learn,你只需要幾行程式碼就能建立一個預測模型。
from sklearn.linear_model import LinearRegression
# 建立簡單的線性回歸模型
model = LinearRegression()
# 訓練模型 (X 為輸入資料,y 為預測目標)
# model.fit(X_train, y_train)
print("模型已準備就緒,隨時可以進行數據預測。")
2. 深度學習 (Deep Learning)
對於影像辨識或語音處理,專家會選用 PyTorch 或 TensorFlow。
3. 生成式 AI 實戰 (Generative AI / LLM)
現在最流行的應用是串接大型語言模型(如 OpenAI 的 GPT 系列)。
import openai
# 呼叫 ChatGPT API 的簡化範例
# response = openai.ChatCompletion.create(
# model="gpt-3.5-turbo",
# messages=[{"role": "user", "content": "用 Python 寫一個笑話"}]
# )
print("這就是開發專屬 AI 聊天機器人的第一步。")
🚀 為什麼 AI 選擇 Python?
- 豐富的生態系: 幾乎所有 AI 論文的參考實作都是用 Python 撰寫的。
- 高效能底層: Python 雖然慢,但 AI 庫的底層多由 C++ 或 CUDA 撰寫,兼顧開發速度與執行效能。
- 社群支援: 遇到問題時,網路上有海量的解決方案與討論。
Python is the backbone of modern AI. From data mining to building your own GPT-powered apps, the possibilities are endless.
✍️ 自我測驗|Self Assessment
Q1: 基礎概念
Python 為何適合初學者?
查看答案
因為語法簡潔、接近英文自然語言、可讀性高,並且有龐大的第三方套件支援。
Because of its simple syntax, readability, and rich ecosystem.
Q2: 迴圈邏輯
for 迴圈與 while 迴圈的主要差別是?
查看答案
for 適用於「已知次數」或「遍歷集合」;while 適用於「未知次數」,直到特定條件滿足為止。
for loops are for known iterations; while loops are for condition-based execution.
Q3: 資料結構 (List)
在 Python 列表 (List) 中,索引值 -1 代表甚麼意思?
查看答案
代表列表中的「最後一個」元素。例如 a[-1] 抓取倒數第一個。
It represents the last element of the list.
Q4: 函式觀念 (Tricky)
函式中的 print() 和 return 有甚麼不同?
查看答案
print 只是把結果「印在螢幕上」,無法被變數儲存;return 會將結果「傳回」給呼叫者,可以存入變數做後續運算。
print displays output; return sends value back to the caller for reuse.
Q5: 字典操作 (Dict)
如果讀取字典中「不存在」的 Key,會發生什麼事?如何安全讀取?
查看答案
直接讀取(如 data["key"])會導致 KeyError 當機。建議使用 data.get("key"),若找不到會回傳 None 而不會報錯。
Direct access raises KeyError. Use .get() method to access safely.
Q6: 資料型別
Tuple (元組) 和 List (列表) 最大的差別是?
查看答案
List 是可變的 (Mutable),可以新增或修改;Tuple 是不可變的 (Immutable),一旦建立就不能修改。
Lists are mutable (changeable); Tuples are immutable.
Q7: 例外處理
在 try...except 結構中,finally 區塊的作用是?
查看答案
無論是否發生錯誤,finally 內的程式碼「一定」會執行。通常用於關閉檔案或資料庫連線。
Code in finally executes regardless of errors, used for cleanup.
📚 延伸學習建議|Next Steps
完成基礎學習後,你的 Python 之旅才剛剛開始。以下是提升競爭力的具體方向:
1. 實戰專案練習 (Portfolio Projects)
不要只看書,動手做這三個經典專案來累積作品集:
- 基礎: 個人理財計算器(處理邏輯與文件讀寫)。
- 自動化: 網路爬蟲(使用
BeautifulSoup抓取即時匯率或新聞)。 - 網頁: 使用
Flask或Django搭建個人 Blog 或 API。
Build projects like a personal budget tracker, a web scraper, or a simple web app using Flask.
2. 磨練邏輯與演算法
提升解題能力,這對於未來的技術面試至關重要:
- LeetCode / Codewars: 每天解 1-2 題,練習資料結構的應用。
- HackerRank: 專注於 Python 專屬挑戰,熟悉語言特性。
Solve coding challenges on LeetCode or Codewars to sharpen your algorithmic thinking.
3. 掌握現代開發工具
從「寫程式」轉向「專業開發」:
- 版本控制: 學習 Git 指令並將代碼託管至 GitHub。
- 自動化測試: 學習使用
pytest,確保代碼更動不會引發錯誤。 - 代碼規範: 閱讀
PEP 8,讓你的代碼看起來像專家寫的。
Learn Git for version control and pytest for automated testing.
4. 推薦學習資源
- 官方文件: docs.python.org — 最權威的百科全書。
- 優質影片: YouTube 頻道(如 Corey Schafer 或 Programming with Mosh)。
- 互動學習: Real Python (網站) 提供深入的技術專題。
Consistency is key. Happy Coding!
⚠️ 初學者常見錯誤|Beginner Mistakes
1. 過度模仿,不理解原理
很多初學者只會複製貼上程式碼,但不理解每一行的作用。這就像是在蓋房子卻不認識磚頭,一旦需求改變,程式就會崩潰。
Understand the "Why" behind the code, not just the "How". Experimenting with code helps solidify concepts.
2. 忽略或害怕錯誤訊息(Error Messages)
Python 的錯誤訊息(Traceback)不是在責備你,而是在告訴你答案。學會閱讀最後一行和行號是關鍵。
# 範例錯誤
File "main.py", line 10, in <module>
result = 10 / 0
ZeroDivisionError: division by zero <-- 這是重點:錯誤原因
The last line of a traceback tells you what went wrong. Don't be afraid; it's a guide to fixing your code.
3. 縮排混亂 (Indentation Issues)
在其他語言中縮排只是為了美觀,但在 Python 中,縮排代表了「邏輯層級」。
# ❌ 錯誤示範
if True:
print("Hello") # 這會導致 IndentationError
# ✅ 正確示範
if True:
print("Hello") # 必須縮排(通常是 4 個空格)
Indentation in Python is functional, not just aesthetic. Always use 4 spaces consistently.
4. 使用無意義的變數名稱
初學者愛用 a, b, c, x1, x2,這會讓你在兩週後回來看程式碼時像是在看無字天書。
# ❌ Bad
d = 86400
# ✅ Good (一眼看出是「一天的秒數」)
seconds_in_a_day = 86400
Choose descriptive names. Code should document itself as much as possible.
5. 把所有程式寫在一起 (Spaghetti Code)
初學者常把數百行邏輯寫在同一個檔案或同一個函式中,導致難易維護與測試。
Avoid "Spaghetti Code". Break logic into small, reusable functions to improve maintainability.
🧠 Python 工程師的思維|How Pythonistas Think
1. 可讀性優先(Readability First)
Python 圈有一句名言:「程式碼是被讀的次數多於被寫的次數。」我們追求簡潔但不過度晦澀。
# ✅ Pythonic (使用 List Comprehension)
numbers = [x * 2 for x in range(5)]
# ❌ Not Recommended (過於繁雜)
numbers = []
for i in range(5):
numbers.append(i * 2)
Code is read much more often than it is written. Python emphasizes readability and expressive code.
2. 善用內建工具與「懶人」哲學
Python 專家會優先使用內建函式(如 sum, zip, enumerate),
而不是自己重寫輪子。這不僅更安全,效能通常也更好。
# ✅ Professional (使用 enumerate 獲取索引)
for index, name in enumerate(["Alice", "Bob"]):
print(f"{index}: {name}")
# ❌ Beginner (手動計算索引)
i = 0
for name in ["Alice", "Bob"]:
print(f"{i}: {name}")
i += 1
Don't reinvent the wheel. Built-in functions are often optimized in C for better performance.
3. 顯式優於隱式 (Explicit is better than Implicit)
這是《Python 禪學》的核心。我們傾向於讓程式碼的功能一目了然,而不是玩弄語法技巧。
# ✅ Clear (明確定義輸入與邏輯)
def get_user_status(is_active):
return "Active" if is_active else "Inactive"
# ❌ Confusing (過度使用隱含邏輯或一行流)
def get_status(a):
return ["Inactive", "Active"][a] # 這樣寫雖然短,但可讀性差
Explicit code is easier to debug and maintain than clever but cryptic one-liners.
4. 問題拆解 (Problem Decomposition)
面對大問題時,先將其拆解為「輸入、處理、輸出」三個小部分,並封裝成獨立函式。
Breaking problems into small, testable functions is a hallmark of professional developers.
5. EAFP 哲學 (容易請求原諒,而非請求許可)
Pythonic 的做法是先執行,出錯了再處理 (Try-Except),而不是寫一堆 if 來檢查。
# ✅ Pythonic (EAFP)
try:
value = my_dict["key"]
except KeyError:
value = "Default"
# ❌ Other Languages Style (LBYL - Look Before You Leap)
if "key" in my_dict:
value = my_dict["key"]
else:
value = "Default"
"Easier to ask for forgiveness than permission" - a common Python coding style.
📝 練習題|Exercises
基礎練習 Beginner
-
撰寫一個函式
is_even(n),判斷輸入的數字是否為偶數。參考解法
def is_even(n): return n % 2 == 0 -
使用
for迴圈印出 1 至 10 的平方。參考解法
for i in range(1, 11): print(i ** 2)
進階挑戰 Challenge
-
撰寫一個函式,接收一個整數列表,回傳最大值與最小值(不可使用
max/min)。參考解法(完整版)
todos = [] def add_task(task): todos.append(task) print(f"Added: {task}") def show_tasks(): print("--- To-Do List ---") if not todos: print("Empty list") for index, task in enumerate(todos, 1): print(f"{index}. {task}") # 測試程式 add_task("Buy milk") add_task("Learn Python") show_tasks() -
設計一個簡單的 Todo 清單程式(使用 list 與 function)。
參考解法(概念示例)
todos = [] def add(todo): todos.append(todo) def show(): for i, t in enumerate(todos, 1): print(i, t)
Exercises are where real learning happens. Try solving before checking the answers.
🗓️ 30 天 Python 自學路線圖|30-Day Learning Roadmap
- Day 1:Python 是甚麼?安裝與環境設定
Expected Outcome:了解 Python 基礎- 了解 Python 定位
- 安裝 Python 與 VS Code
- 能運行第一個程式
- Day 2:變數、資料型別、print
Expected Outcome:掌握基礎資料操作- 宣告變數
- 使用基本資料型別
- 使用 print 輸出
- Day 3:字串、數字運算
Expected Outcome:能操作文字與數字- 字串基本操作
- 數字運算
- 組合運算與格式化
- Day 4:if / else 條件判斷
Expected Outcome:能判斷條件- 寫 if 條件
- 寫 else 條件
- 能組合多條件
- Day 5:for / while 迴圈
Expected Outcome:能使用迴圈- 寫 for 迴圈
- 寫 while 迴圈
- 能控制迴圈流程
- Day 6:綜合練習(小計算器)
Expected Outcome:整合應用- 能設計簡單程式
- 能使用變數與運算
- 輸出正確結果
- Day 7:回顧與整理筆記
Expected Outcome:加深記憶- 回顧前 6 天內容
- 整理筆記
- 標註不懂的地方
- Day 8:函式
Expected Outcome:能封裝邏輯- 我會定義函式
- 我會回傳值
- 我能重用函式
- Day 9:List / Tuple / Dict
Expected Outcome:能操作資料結構- 我知道各自用途
- 我能新增 / 存取資料
- 我能遍歷集合
- Day 10:資料處理
Expected Outcome:能操作集合資料- 我能修改資料
- 我能搜尋資料
- 我能寫小練習
- Day 11:模組與 import
Expected Outcome:能拆分程式- 我能 import 模組
- 我知道 __name__ 用途
- 我能拆檔案
- Day 12:例外處理
Expected Outcome:程式不易當掉- 我會 try / except
- 我能處理錯誤
- 我理解 traceback
- Day 13:檔案 I/O
Expected Outcome:能讀寫檔案- 我能讀檔
- 我能寫檔
- 我理解檔案路徑
- Day 14:Todo CLI 專案
Expected Outcome:完成小系統- 我能新增事項
- 我能顯示清單
- 程式可反覆使用
- Day 15:Class / Object
Expected Outcome:能設計類別- 我能寫 class
- 我理解物件概念
- 我能實例化物件
- Day 16:OOP 實作
Expected Outcome:能設計互動類別- 我能設計方法
- 我能用屬性
- 類別設計合理
- Day 17:List Comprehension
Expected Outcome:能簡化程式碼- 我能寫 comprehension
- 我理解可讀性
- 我能重構舊碼
- Day 18:Pythonic 重構
Expected Outcome:程式更乾淨- 我能刪冗餘程式
- 我能改善命名
- 我理解可維護性
- Day 19:標準函式庫
Expected Outcome:能查文件用模組- 我能用 datetime
- 我能用 random
- 我會查官方文件
- Day 20:Debug
Expected Outcome:能快速找錯- 我能看錯誤訊息
- 我會逐步檢查
- 我能修正 bug
- Day 21:專案重構
Expected Outcome:提升品質- 結構更清楚
- 命名更合理
- 程式更好讀
- Day 22:專案規劃
Expected Outcome:能拆需求- 我能畫出流程
- 我能列出模組
- 我知道實作順序
- Day 23:自動化腳本
Expected Outcome:能解決實際問題- 腳本可重複用
- 能節省時間
- 有實際用途
- Day 24:資料處理
Expected Outcome:能處理真實資料- 我能清洗資料
- 我能轉換格式
- 我理解資料流程
- Day 25:測試思維
Expected Outcome:理解測試價值- 我會寫基本測試
- 我知道測什麼
- 程式更安心
- Day 26:文件與註解
Expected Outcome:程式他人能懂- 我會寫 README
- 註解清楚
- 結構一致
- Day 27:效能與可讀性
Expected Outcome:做出工程取捨- 我能衡量效能
- 我不過度優化
- 程式可維護
- Day 28–30:Final Project
Expected Outcome:完成完整專案- 專案可展示
- 能清楚說明設計
- 我有自信說:我會 Python
🗓️ 30 天 Python 自學路線圖|30-Day Learning Roadmap
每天完成後,請逐項檢查 Self-Check Checklist。若有未完成項目,可參考 Debug / 卡關提示。
Verify each checklist item. Use Debug / Tips if stuck.
第 1 週|基礎打底 Fundamentals
- Day 1:安裝與第一個程式
Expected Outcome:能成功執行 Python 程式Debug Tip:若python --version無法執行,請確認 PATH 是否設定正確。If python command fails, check environment PATH variable. - Day 2:變數與資料型別
Expected Outcome:能使用基本型別Debug Tip:出現 TypeError 時,確認資料型別一致。If TypeError occurs, ensure variable types match. - Day 3:字串與運算
Expected Outcome:能處理數字與文字Debug Tip:使用 f-string 時,確認 Python 版本 >= 3.6。f-strings require Python 3.6 or newer. - Day 4:if / else
Expected Outcome:能控制流程Debug Tip:縮排錯誤是最常見的 if 語法問題。IndentationError is common in if statements. - Day 5:for / while
Expected Outcome:能使用迴圈Debug Tip:while 迴圈請注意退出條件,避免無限迴圈。Ensure while loops have a termination condition. - Day 6:小計算器
Expected Outcome:完成第一個程式Debug Tip:接收使用者輸入時,確認使用 int() 或 float() 轉型。Convert input using int() or float() when needed. - Day 7:回顧
Expected Outcome:能解釋所有基礎Debug Tip:回顧時將程式碼寫出來,比單純看筆記更有效。Writing code while reviewing is more effective than just reading notes.
提示:請確保每個 Debug Tip 都理解並測試過。
Make sure to understand and test each Debug Tip.
第 2 週|資料結構與函式 Data Structures & Functions
- Day 8:函式
Expected Outcome:能封裝邏輯與重複使用Debug Tip:若函式回傳None,檢查是否忘記寫return。If function returns None, check if you forgot the return statement. - Day 9:List / Tuple / Dict
Expected Outcome:能操作集合資料Debug Tip:IndexError表示超出範圍;KeyError表示字典找不到該鍵。IndexError means list is too short; KeyError means key doesn't exist. - Day 10:資料處理
Expected Outcome:能修改與搜尋資料Debug Tip:避免在for迴圈遍歷列表時直接刪除元素,會導致跳號。Avoid removing items from a list while iterating over it. - Day 11:模組與 import
Expected Outcome:能拆分程式檔案Debug Tip:不要將自己的檔案命名為與內建模組相同(如random.py)。Do not name your files the same as standard libraries (e.g., random.py). - Day 12:例外處理
Expected Outcome:程式遇到錯誤不崩潰Debug Tip:盡量捕捉特定錯誤(如ValueError),避免使用裸except:。Catch specific errors (e.g., ValueError) rather than using a bare except. - Day 13:檔案 I/O
Expected Outcome:能讀寫文字檔Debug Tip:使用with open(...)區塊,確保檔案會自動關閉。Use 'with open(...)' block to ensure files are closed automatically. - Day 14:Todo CLI 專案
Expected Outcome:完成 CRUD 小系統Debug Tip:在無窮迴圈中,務必設定break條件讓使用者離開程式。Ensure a 'break' condition exists to exit the infinite loop.
第 3 週|物件導向與進階 OOP & Advanced
- Day 15:Class / Object
Expected Outcome:能定義類別與物件Debug Tip:定義方法時,第一個參數必須是self。The first argument of instance methods must be 'self'. - Day 16:OOP 實作
Expected Outcome:能設計屬性與方法Debug Tip:__init__是初始化方法,不能有return值。__init__ is for initialization and cannot return a value. - Day 17:List Comprehension
Expected Outcome:能寫出簡潔語法Debug Tip:若邏輯太過複雜導致難以閱讀,請改回使用普通迴圈。If logic is too complex, stick to normal loops for readability. - Day 18:Pythonic 重構
Expected Outcome:程式碼更符合規範Debug Tip:重構不應改變程式行為,修改後務必重新測試。Refactoring shouldn't change behavior. Always re-test after changes. - Day 19:標準函式庫
Expected Outcome:能善用現成工具Debug Tip:造輪子前先查文件,很多功能collections或itertools都有。Check standard docs before reinventing the wheel. - Day 20:Debug
Expected Outcome:能獨立解決 BugDebug Tip:學會使用 VS Code 的斷點(Breakpoint),比一直 print 有效。Learn to use breakpoints in VS Code instead of just print(). - Day 21:專案重構
Expected Outcome:模組化既有程式Debug Tip:若一個函式超過 20 行,思考是否該拆分成兩個小函式。If a function is over 20 lines, consider splitting it.
第 4 週|專業實戰 Professional Practices
- Day 22:專案規劃
Expected Outcome:產出架構圖與流程Debug Tip:不要急著寫 code,先用紙筆畫出流程圖 (Flowchart)。Don't code yet. Draw a flowchart first.
Day 23:自動化實戰 Week - Day 24:資料處理實戰
Expected Outcome:清洗髒資料Debug Tip:讀取外部資料時,永遠先做strip()去除前後空白。Always use strip() to clean whitespace from external inputs. - Day 25:AI 啟蒙 - 數據的威力
Expected Outcome:使用Pandas讀取 CSV 並進行基礎統計。Debug Tip:確保數據沒有空值(NaN),這會影響 AI 的判斷。Data cleaning is the first step of AI. - Day 26:機器學習初體驗
Expected Outcome:理解「特徵 (Features)」與「標籤 (Labels)」,並跑通第一個線性回歸。核心觀念:機器學習就是找出一條最符合數據趨勢的數學公式。 - Day 27:生成式 AI 與 API 串接
Expected Outcome:學會使用requests呼叫 OpenAI API 或類似的 AI 服務。實作建議:嘗試寫一個「AI 翻譯官」小工具。LLMs extend Python's capability to natural language tasks. - Day 28:深度學習觀念建立
Expected Outcome:認識神經網路與 GPU 加算的重要性。知道即可:了解PyTorch是目前學術與工業界最主流的 AI 框架。 - Day 29:綜合大專案 - 我的 AI 小助手
Expected Outcome:結合爬蟲 (BS4) + 數據處理 (Pandas) + AI API,做出一個能總結網頁資訊的工具。 - Day 30:專家之路與結業
Expected Outcome:回顧所有 Checkbox,並規劃下一階段的專精領域。恭喜!你已經從零開始,走到了 AI 開發的門檻前。Congratulations! You've completed the 30-day challenge.
Expected Outcome:完成一個自動化腳本(如:自動整理桌面檔案或抓取即時匯率)。
os, shutil, requests。🐍 Python 互動實驗室 引擎啟動中...
在左/上方撰寫程式碼,透過「一般執行」練習,或透過「挑戰模式」解鎖進度。
💡 點擊教學章節中的「🚀 執行」按鈕,即可在此載入對應的挑戰任務。