Python 學習手冊

Python 自學指南

從零變專家 · From Zero to Expert

前言|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 的常見用途

第 2 章|安裝與環境設定 Setup

建議初學者使用官方 Python 以及 VS Code (Visual Studio Code) 作為開發環境,這是目前業界最主流的組合。

1. 安裝 Python

前往 python.org 下載最新版本。

⚠️ 重要: 安裝時務必勾選 "Add Python to PATH",否則你在終端機將無法執行 python 指令。

Crucial: Make sure to check "Add Python to PATH" during installation.

2. 設定 VS Code 開發環境

安裝完 VS Code 後,請在「擴充功能 (Extensions)」搜尋並安裝以下插件:

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 的命名風格能讓你的程式碼更專業:

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

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)

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.

第 5.3 章: 非同步程式設計 (AsyncIO)

在傳統的 Python 程式中,程式碼是「同步」執行的,這意味著如果一個任務在等待(例如下載大檔案),整個程式都會停下來。asyncio 允許我們在等待 I/O 時執行其他任務。

💡 核心觀念: 非同步就像是在餐廳:服務生(CPU)點完餐後不需要在廚房門口等菜好,可以先去幫別桌服務。

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())

第 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)

不要試圖學習所有東西,先深耕一個方向:

Focus on one domain: Data Science, Web Dev, or Automation/Scripting.

2. 撰寫「工程級」代碼 (Writing Production-Ready Code)

專家與業餘者的區別在於程式碼的可維護性:

3. 深入底層原理 (Understanding the Internals)

理解 Python 是如何運作的,能幫你寫出效能更高的程式:

進階課題: 記憶體管理 (Garbage Collection)、全域解釋器鎖 (GIL)、以及裝飾器 (Decorators) 的底層機制。

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)

對於影像辨識或語音處理,專家會選用 PyTorchTensorFlow

提示: 這些框架通常需要配合 GPU 運算來提升訓練速度。

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?

  1. 豐富的生態系: 幾乎所有 AI 論文的參考實作都是用 Python 撰寫的。
  2. 高效能底層: Python 雖然慢,但 AI 庫的底層多由 C++ 或 CUDA 撰寫,兼顧開發速度與執行效能。
  3. 社群支援: 遇到問題時,網路上有海量的解決方案與討論。

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)

不要只看書,動手做這三個經典專案來累積作品集:

Build projects like a personal budget tracker, a web scraper, or a simple web app using Flask.

2. 磨練邏輯與演算法

提升解題能力,這對於未來的技術面試至關重要:

Solve coding challenges on LeetCode or Codewars to sharpen your algorithmic thinking.

3. 掌握現代開發工具

從「寫程式」轉向「專業開發」:

Learn Git for version control and pytest for automated testing.

4. 推薦學習資源

💡 專家建議: 嘗試閱讀別人的開源專案(Open Source),這是學習「優雅代碼」最快的方式。

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)

初學者常把數百行邏輯寫在同一個檔案或同一個函式中,導致難易維護與測試。

解法: 善用第 5 章學過的「函式」,將大型任務拆解成多個小任務。

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)

面對大問題時,先將其拆解為「輸入、處理、輸出」三個小部分,並封裝成獨立函式。

工程思維: 一個函式只做一件事情 (Single Responsibility Principle)。

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

  1. 撰寫一個函式 is_even(n),判斷輸入的數字是否為偶數。
    參考解法
    def is_even(n):
        return n % 2 == 0
  2. 使用 for 迴圈印出 1 至 10 的平方。
    參考解法
    for i in range(1, 11):
        print(i ** 2)

進階挑戰 Challenge

  1. 撰寫一個函式,接收一個整數列表,回傳最大值與最小值(不可使用 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()
  2. 設計一個簡單的 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

🗓️ 30 天 Python 自學路線圖|30-Day Learning Roadmap

每天完成後,請逐項檢查 Self-Check Checklist。若有未完成項目,可參考 Debug / 卡關提示

Verify each checklist item. Use Debug / Tips if stuck.

第 1 週|基礎打底 Fundamentals

提示:請確保每個 Debug Tip 都理解並測試過。

Make sure to understand and test each Debug Tip.

第 2 週|資料結構與函式 Data Structures & Functions

第 3 週|物件導向與進階 OOP & Advanced

第 4 週|專業實戰 Professional Practices

🐍 Python 互動實驗室 引擎啟動中...

在左/上方撰寫程式碼,透過「一般執行」練習,或透過「挑戰模式」解鎖進度。

正在下載 Python 核心 (Pyodide)...

等待執行...

💡 點擊教學章節中的「🚀 執行」按鈕,即可在此載入對應的挑戰任務。