Python 101:開始寫 AI 專案前真正需要的語法
環境建好了之後,這篇接著整理 Python 的核心語法——不貪多,只講你做 AI 專案前真正會用到的部分。所有範例都可以直接貼進 .py 檔執行。
變數與資料型別
變數就是「儲存資料的容器」,Python 不需要宣告型別,會自動判斷。
name = "Alice" # str 字串
age = 20 # int 整數
gpa = 3.85 # float 浮點數
is_student = True # bool 布林值
print(name) # Alice
print(type(age)) # <class 'int'>
# 字串格式化 (f-string)
print(f"{name} is {age} years old") # Alice is 20 years old
幾個重點:
- 動態型別:Python 會自動判斷型別,不用像 Java 那樣寫
int x = 10。 =是賦值,把右邊的值存到左邊的變數名稱裡。#是註解,寫給人看的,Python 會忽略。- f-string(
f"...{變數}...")可以在字串中嵌入變數,超好用。
條件判斷與迴圈
# 條件判斷 if / elif / else
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("C")
# 輸出:B
# for 迴圈
for i in range(5): # 從 0 到 4
print(i) # 0, 1, 2, 3, 4
# 走訪清單
for fruit in ["apple", "banana"]:
print(fruit) # apple, banana
# while 迴圈
count = 0
while count < 3: # 只要 count 小於 3 就一直跑
count += 1 # 所以會跑三次
Python 用縮排取代大括號,縮排錯誤就是語法錯誤。建議用 4 個空格(VS Code 預設)。另外 range(n) 會產生 0 到 n-1,range(2, 7) 則是 2, 3, 4, 5, 6。
List 與 Dictionary
這是 AI 時代最常用的兩個資料結構:List 裝一堆同類的東西(例如多筆對話記錄),Dict 裝有欄位名的資料(例如 API 回傳的 JSON)。
# List(清單)— 有序、可修改
nums = [10, 20, 30, 40]
print(nums[0]) # 10
print(nums[-1]) # 40(最後一個)
nums.append(50) # 新增到最後
nums.pop() # 移除最後一個
print(len(nums)) # 長度
print(nums[1:3]) # 切片 → [20, 30]
# Dictionary(字典)— key-value 配對
student = {
"name": "Alice",
"age": 20,
"major": "CS",
}
print(student["name"]) # Alice(用 key 取 value)
student["gpa"] = 3.85 # 新增 / 修改
for k, v in student.items():
print(f"{k}: {v}")
函式(Function)
函式就是「可以重複使用的程式碼區塊」。寫好函式 = 少寫重複 code = 更好 debug、更好維護。
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# 有預設值的參數(預設次方是 2)
def power(base, exp=2):
return base ** exp
print(power(3)) # 9 (3^2)
print(power(3, 3)) # 27 (3^3)
# 回傳多個值
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([3, 1, 4, 1, 5])
print(lo, hi) # 1 5
def是定義函式的關鍵字。- 括號裡的是參數(parameter),也就是輸入。
return把結果回傳給呼叫者。- 用
函式名(引數)來呼叫。
Class(類別)— 先聽聽就好
剛開始不用急著寫,但 API 回傳的資料常用 Class 封裝,看得懂就好:
class Dog:
"""一隻狗的藍圖(類別)"""
def __init__(self, name, breed): # 建立物件時自動執行
self.name = name # 屬性
self.breed = breed
def bark(self): # 方法(物件的行為)
return f"{self.name} says Woof!"
my_dog = Dog("Mochi", "Shiba") # 建立物件(實例化)
print(my_dog.bark()) # Mochi says Woof!
核心概念:Class 是藍圖(定義某種東西的模板),Object 是用藍圖造出來的實體。__init__ 是建構子,self 代表「這個物件自己」,self.xxx 是屬性,def xxx(self) 是方法。
怎麼讀懂一份 Python 程式?
拿到一份 code 不要從頭硬讀,照這個順序看:
# 1. import 區域:引入需要的工具
import requests
from datetime import datetime
# 2. 函式定義區
def get_weather(city):
"""取得城市的天氣資訊"""
url = f"https://api.weather.com/{city}"
response = requests.get(url)
return response.json()
# 3. 主程式入口
if __name__ == "__main__":
data = get_weather("Taipei")
print(f"溫度:{data['temp']}°C")
- 先看 import——用了什麼套件?大概知道功能方向。
- 看函式定義——每個
def做什麼?看名稱和 docstring。 - 找主入口——有
if __name__ == "__main__"就是程式啟動的地方;沒有的話就從上往下讀。 - 追蹤資料流——變數從哪來、傳到哪去。
時間不夠的話,先學這些
- 變數 & 型別:
str/int/float/bool,資料的基本單位。 if/for/while:程式邏輯的核心。- List & Dict:處理 API 回傳的 JSON 必備。
- 函式
def:把重複邏輯包起來。 uv add:安裝第三方套件,用別人寫好的工具。- 加分:f-string &
print(debug 最好的朋友)、try/except(讓程式不會因為一個 bug 就整個崩潰)。
掌握這些,就能開始做 AI 專案了。
動手練習
# 練習 1:Hello World(存成 hello.py,然後 python hello.py)
name = input("你叫什麼名字?")
print(f"Hello, {name}!")
# 練習 2:FizzBuzz
for i in range(1, 16):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
進階挑戰:用 uv add google-genai 裝好 SDK,然後用「Vibe Coding」的精神——把你想做的事告訴 AI 就好,請它幫你寫一個用 Gemini API 的簡單聊天機器人(記得提醒它保護好你的 API Key)。
想再深入的學習資源
- 盧信銘老師的快速教學——資管系老師的精華版,20 分鐘就能有感覺:影片一、影片二。
- Papaya 的詳細 Python 系列——從淺到深,適合系統學習。
- 四小時略懂 Python(我阿嬤都會)——零基礎入門、語速親民:影片。
- Coursera 商管程式設計課程——想學習之餘還拿證書就選這門:課程連結。
不確定看哪個?先看盧信銘老師那部就對了。
語法是工具,重點是動手做。把上面的範例都跑過一遍,你就準備好開始寫第一個 AI 專案了。
這系列是我在 NTU AI Club 和 datafox.tw 一起完成的課程。