—— 用一個專案學會流程控制、函式、字串與 API 思維
在這個教學中,我們將透過一個 **「Python 自動氣象播報員」**的小專案,學會多個非常重要的 Python 基礎觀念,包括:
✅ 函式(Function)
✅ 條件判斷(if / elif / else)✅ 字串處理(String)
✅ 字典與串列(Dictionary & List)
✅ f-string 格式化輸出
✅ API 與 JSON 的基本概念
📌 專案目標說明
這個程式可以讓使用者:
- 輸入想查詢的城市
- 取得該城市的氣溫與天氣描述(以 API 資料格式模擬)
- 根據天氣狀況,自動給出穿衣與生活建議
🧱 專案整體架構
程式主要分成三個部分:
- get_weather_advice()
👉 根據氣溫與天氣狀況,產生貼心建議 - weather_reporter()
👉 主程式,負責使用者互動與資料整合 - 主程式進入點 (if __name__ == "__main__":)
1️⃣ 匯入套件:requests
import requests
這行是用來匯入 requests 套件,它的用途是:
- 向網路 API 發送請求
- 取得 JSON 格式的資料
📌 本教學中先不實際呼叫 API,而是用模擬資料,讓初學者能專心理解邏輯。
2️⃣ 撰寫天氣建議函式 get_weather_advice
def get_weather_advice(temp, condition):
"""
根據氣溫和天氣狀況提供穿衣與生活建議
"""
🔹 函式參數說明
temp:目前氣溫(數字)condition:天氣描述(字串)
🔸 條件判斷(if / elif / else)
if temp < 15:
advice += "❄️ 今天很冷,記得穿上厚外套喔!"
elif 15 <= temp <= 25:
advice += "☁️ 氣溫舒適,穿件薄長袖或外套就可以了。"
else:
advice += "☀️ 天氣炎熱,多喝水注意防曬!"
📘 這一段示範了:
- 數值比較
- 多重條件判斷
- 根據不同情況給出不同結果
🔸 字串處理(檢查是否下雨)
if "rain" in condition.lower() or "雨" in condition:
advice += "\n☔ 外面好像會下雨,出門記得帶把傘。"
📘 這裡學到:
.lower():把字串轉成小寫in:檢查字串是否包含某個關鍵字- 換行字元
\n
🔸 回傳結果
return advice
這樣主程式就可以拿到整理好的建議內容。
3️⃣ 主程式:weather_reporter()
def weather_reporter():
這是整個應用程式的核心。
🔹 使用者輸入
city = input("請輸入你想查詢的城市名稱: ")
📘 讓使用者與程式互動,是寫應用程式的第一步。
🔹 API 網址(示意)
api_url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid=YOUR_API_KEY_HERE"
📘 這一行示範:
- f-string
- API Query 的基本結構
- 為未來串接真實 API 做準備
4️⃣ 模擬 API 回傳資料(JSON 結構)
sample_data = {
"main": {"temp": 22.5, "humidity": 70},
"weather": [{"description": "clear sky"}],
"name": city
}
📘 這段非常重要,因為:
- API 回傳的資料通常是 JSON
- 在 Python 中會轉成 Dictionary + List
🔹 資料提取(容器操作)
current_temp = sample_data["main"]["temp"]
weather_desc = sample_data["weather"][0]["description"]
📘 學到:
- 字典取值
- 串列索引
- 巢狀資料結構存取
5️⃣ 呼叫函式,取得建議
my_advice = get_weather_advice(current_temp, weather_desc)
📘 這就是「函式的價值」:
- 把複雜邏輯包起來
- 主程式變得乾淨又好讀
6️⃣ 美化輸出(f-string)
print(f"🌡️ 當前氣溫:{current_temp}°C")
print(f"💡 貼心建議:{my_advice}")
📘 f-string 的好處:
- 可讀性高
- 適合顯示動態資料
- 幾乎是 Python 必學技能
7️⃣ 程式進入點
if __name__ == "__main__":
weather_reporter()
📘 這行的意思是:
- 只有在直接執行此檔案時,才會啟動程式
- 是 Python 專業寫法的基本配備
完整程式碼
import requests
def get_weather_advice(temp, condition):
"""
根據氣溫和天氣狀況提供穿衣與生活建議 (流程控制練習)
"""
advice = ""
# 1. 針對溫度的建議 (if-elif-else)
if temp < 15:
advice += "❄️ 今天很冷,記得穿上厚外套喔!"
elif 15 <= temp <= 25:
advice += "☁️ 氣溫舒適,穿件薄長袖或外套就可以了。"
else:
advice += "☀️ 天氣炎熱,多喝水注意防曬!"
# 2. 針對天氣描述的建議 (字串處理)
if "rain" in condition.lower() or "雨" in condition:
advice += "\n☔ 外面好像會下雨,出門記得帶把傘。"
return advice
def weather_reporter():
print("--- 🌟 歡迎使用 Python 自動氣象播報員 🌟 ---")
city = input("請輸入你想查詢的城市名稱 (例如: Taipei 或 London): ")
# 這裡使用一個開放的 API 範例 (OpenWeatherMap 邏輯)
# 註:實際教學時,學員需申請 API Key,此處為演示邏輯
api_url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid=YOUR_API_KEY_HERE"
print(f"\n正在幫你連線到雲端資料庫,查詢 {city} 的天氣...")
# 模擬 API 回傳的資料結構 (Dictionary & List 練習)
# 在實際影片中,我們會解釋這是 Requests 抓回來的 JSON 格式
sample_data = {
"main": {"temp": 22.5, "humidity": 70},
"weather": [{"description": "clear sky"}],
"name": city
}
# 提取資料 (容器操作)
current_temp = sample_data["main"]["temp"]
weather_desc = sample_data["weather"][0]["description"]
# 取得建議 (呼叫函式)
my_advice = get_weather_advice(current_temp, weather_desc)
# 華麗的字串輸出 (f-string)
print("-" * 40)
print(f"📍 城市位置:{sample_data['name']}")
print(f"🌡️ 當前氣溫:{current_temp}°C")
print(f"☁️ 天氣狀況:{weather_desc}")
print(f"💡 貼心建議:{my_advice}")
print("-" * 40)
print("祝你有美好的一天!畢業快樂!🎓")
if __name__ == "__main__":
weather_reporter()
🎯 教學重點總結
透過這個小專案,你已經學會了:
✔ 如何設計與呼叫函式
✔ 如何使用條件判斷處理不同情況
✔ 如何操作 Dictionary 與 List
✔ 如何理解 API 與 JSON 的資料結構
✔ 如何寫出有「實用價值」的 Python 程式


















