入門 · 免費

Python 入門(免費完整課)

免費公開課 · 約 20–40 分鐘 · 聯絡 psyche@mail.grokbot.com

一句話:裝好 Python、寫出第一支腳本、用變數/迴圈/函數做出一個小工具,就完成這堂課。

本課用免費工具(官方安裝包、VS Code/Cursor 免費版、內建標準庫)。不需付費 API。

1. 安裝環境(約 10 分鐘)

  1. 到 python.org/downloads 下載最新穩定版(3.12+)。
  2. Windows:安裝時勾選 Add python.exe to PATH。
  3. macOS/Linux:可用官方安裝包或套件管理器。
  4. 開終端機驗證:
python3 --version
# Windows 若無效可試:python --version

編輯器(擇一)

  • VS Code + Python 擴充
  • Cursor(AI 輔助編輯,免費額度可用)
  • 或直接用終端:python3 進入互動模式

2. 第一支程式:Hello + 變數

新建檔案 hello.py:

# hello.py
name = "Psyche"
age = 30
print("你好,", name)
print(f"{name} 今年 {age} 歲")  # f-string:把變數嵌進字串

# 常見型別
price = 39.0          # float
is_member = True      # bool
tags = ["AI", "Python"]  # list
profile = {"city": "HK", "level": "入門"}  # dict

執行:

python3 hello.py

3. 條件判斷與迴圈

# grade.py
score = 85
if score >= 90:
    level = "A"
elif score >= 70:
    level = "B"
else:
    level = "C"
print("等級:", level)

# 迴圈:處理清單
tasks = ["安裝 Python", "寫 hello", "做練習"]
for i, t in enumerate(tasks, start=1):
    print(f"{i}. {t}")

# while:倒數
n = 3
while n > 0:
    print("倒數", n)
    n -= 1
print("開始!")

4. 函數:把重複邏輯包起來

# calc.py
def add(a, b):
    """回傳兩數之和"""
    return a + b

def summarize(items):
    total = 0
    for x in items:
        total += x
    avg = total / len(items) if items else 0
    return {"sum": total, "avg": avg, "count": len(items)}

print(add(3, 5))
print(summarize([10, 20, 30]))

5. 迷你專案:命令列待辦清單

存成 todo.py,用純文字檔保存,不需資料庫:

# todo.py
from pathlib import Path

FILE = Path("todos.txt")

def load():
    if not FILE.exists():
        return []
    return [line.strip() for line in FILE.read_text(encoding="utf-8").splitlines() if line.strip()]

def save(items):
    FILE.write_text("\n".join(items) + ("\n" if items else ""), encoding="utf-8")

def main():
    items = load()
    while True:
        print("\n1 列出  2 新增  3 刪除  0 離開")
        choice = input("> ").strip()
        if choice == "1":
            for i, t in enumerate(items, 1):
                print(f"{i}. {t}")
        elif choice == "2":
            t = input("內容:").strip()
            if t:
                items.append(t)
                save(items)
        elif choice == "3":
            n = int(input("刪第幾項:"))
            if 1 <= n <= len(items):
                items.pop(n - 1)
                save(items)
        elif choice == "0":
            break
        else:
            print("無效選項")

if __name__ == "__main__":
    main()

練習(請自己做)

  1. 改寫 todo.py:新增「標記完成」功能(例如在文字前加 [x])。
  2. 寫一個 bmi.py:輸入身高(cm)與體重(kg),輸出 BMI 與簡易建議。
  3. (選做)用 json 模組把待辦改存成 todos.json。

完成標準:能獨立執行、無報錯、知道 if / for / def 各做什麼。

常見問題

  • 找不到 python:重開終端;確認 PATH;Windows 試 py -3。
  • 中文亂碼:檔案存 UTF-8;讀寫時指定 encoding="utf-8"。
  • IndentationError:用空白縮排(建議 4 格),不要混 Tab。

學習進度

登入會員後可標記完成並同步至儀表板。