一起玩Python程式:新手寫程式也可以這麼簡單!

Week 04: 流程控制(上) - 程式的決策之道!

張傑帆

National Taiwan University

流程控制(上) - 程式的決策之道!

目錄

Alt1

🎯 學習目標

今天我們要讓程式學會做決定!

🔧 技能解鎖清單:

  • 條件判斷掌握 - 讓程式會思考(判斷) 🧠
  • 比較運算精通 - 判斷大小多少 📊
  • 邏輯思維建立 - 複雜條件組合 🔗
  • 選單系統設計 - 使用者友善介面 📋
  • 隨機功能應用 - 增加程式趣味性 🎲
  • 決策系統整合 - 打造智慧助手 🤖

Let's make smart programs! 🚀✨

🧠 什麼是流程控制?

生活中的決策

  • 🌧️ 下雨了 → 帶傘出門
  • ☀️ 天氣晴朗 → 不帶傘
  • 🎯 考試成績 ≥ 80 → 獎勵自己
  • 📱 手機電量 < 20% → 開始充電

程式中的流程控制

if 條件:
    執行動作A
else:
    執行動作B

讓程式能根據不同情況做出不同反應

🤔 if-else條件判斷基礎

基本語法結構

if 條件式:
    # 條件為True時執行
    程式碼塊
else:
    # 條件為False時執行
    程式碼塊

🌡️ 溫度判斷範例

temperature = int(input("今天溫度是幾度?"))

if temperature >= 25:
    print("今天很熱,記得多喝水!🌞")
else:
    print("今天涼爽,適合出門走走!🚶")

重點提醒:Python用縮排來表示程式碼塊!

🔍 比較運算符號大解密

六大比較運算符

符號 意義 範例 結果
== 等於 5 == 5 True
!= 不等於 5 != 3 True
> 大於 8 > 5 True
< 小於 3 < 7 True
>= 大於等於 5 >= 5 True
<= 小於等於 4 <= 6 True

🎯 實戰範例

score = 85

# 基本比較運算
print(score >= 80)    # True
print(score == 100)   # False

# 結合if條件判斷
if score >= 80:
  print("恭喜!成績優良!🎉")

if score != 100:
  print("還有進步空間喔!💪")

# 更多比較範例
age = 18
if age >= 18:
  print("已成年,可以投票!🗳")

temperature = 30
if temperature > 25:
  print("今天很熱!🌞")

⚡ 邏輯運算符號應用

三大邏輯運算符

運算符 功能 範例 說明
and True and True 兩個都要是True
or True or False 至少一個是True
not not True 相反的布林值

🎓 成績分級範例

score = int(input("請輸入成績:"))

if score >= 90 and score <= 100:
    print("A級:優秀!🏆")
elif score >= 80 and score < 90:
    print("B級:良好!👍")
elif score >= 70 and score < 80:
    print("C級:及格!✅")
else:
    print("需要加油!💪")

🎯 多重條件判斷(elif)

elif語法結構

if 條件1:
    動作1
elif 條件2:
    動作2
elif 條件3:
    動作3
else:
    其他動作

🚦 交通燈號系統

light = input("交通號誌是什麼顏色?(紅/黃/綠)")

if light == "紅":
    print("🔴 停止!等待綠燈")
elif light == "黃":
    print("🟡 準備停車,注意安全")
elif light == "綠":
    print("🟢 可以通行")
else:
    print("❓ 無效的號誌顏色")

🎮 互動式選單設計 - 選單系統範例

print("=== 🍕 歡迎來到Pizza店 ===")
print("1. 瑪格麗特披薩 - $280")
print("2. 夏威夷披薩 - $320") 
print("3. 海鮮披薩 - $380")
print("4. 離開")

choice = input("請選擇您要的披薩(1-4):")

if choice == "1":
    print("您選擇了瑪格麗特披薩!🍕")
elif choice == "2":
    print("您選擇了夏威夷披薩!🍍")
elif choice == "3":
    print("您選擇了海鮮披薩!🦐")
elif choice == "4":
    print("謝謝光臨!👋")
else:
    print("無效選擇,請重新選擇!")

小練習

print("=== 📚 學生成績管理系統 ===")

# 輸入成績
chinese = int(input("請輸入國文成績:"))
english = int(input("請輸入英文成績:"))
math = int(input("請輸入數學成績:"))

# 計算總分和平均
total = chinese + english + math
average = total / 3

print(f"總分:{total}")
print(f"平均:{average:.1f}")

# 成績等級判斷
if average >= 90:
  print("🏆 A級:優秀!")
  print("建議:...")
elif average >= 80:
  print("👍 B級:良好!")
  print("建議:...")
elif average >= 70:
  print("✅ C級:及格!")
  print("建議:...")
elif average >= 60:
  print("⚠ D級:待加強!")
  print("建議:...")
else:
  print("💪 E級:需努力!")
  print("建議:...")

🎲 Random模組

Random模組是Python的內建模組,用來產生隨機數字、隨機選擇等功能

基本使用方法

import random  # 首先要匯入模組

常用Random函式

1. random.randint(a, b) - 產生整數範圍隨機數

import random

# 產生1到10之間的隨機整數(包含1和10)
dice = random.randint(1, 6)    # 骰子
lottery = random.randint(1, 49) # 樂透號碼

2. random.choice(sequence) - 從序列中隨機選擇

# 從清單中隨機選一個
colors = ["紅色", "藍色", "綠色", "黃色"]
chosen_color = random.choice(colors)

# 隨機選擇今天要做的事
activities = ["看電影", "運動", "讀書", "購物"]
today_plan = random.choice(activities)

3. random.random() - 產生0-1之間的小數

# 產生0.0到1.0之間的隨機小數
probability = random.random()
print(f"機率值:{probability}")

# 模擬擲硬幣
if random.random() > 0.5:
  print("正面!")
else:
  print("反面!")

4. random.shuffle(list) - 打亂清單順序

# 洗牌功能
cards = ["A", "K", "Q", "J", "10"]
random.shuffle(cards)
print(f"洗牌後:{cards}")

🎲 Random模組增添趣味

引入random模組

import random

# 產生1-10的隨機數字
number = random.randint(1, 10)
print(f"隨機數字:{number}")

# 從清單中隨機選擇
foods = ["漢堡", "壽司", "義大利麵", "炒飯"]
choice = random.choice(foods)
print(f"今天吃:{choice}")

🎯 猜數字遊戲

import random

secret = random.randint(1, 100)
guess = int(input("猜一個1-100的數字:"))

if guess == secret:
    print("🎉 恭喜!猜對了!")
elif guess > secret:
    print("📉 太大了!")
else:
    print("📈 太小了!")

🎯 實戰範例:運勢占卜器

import random

print("🔮 今日運勢占卜器 🔮")
name = input("請輸入您的姓名:")

# 隨機運勢
fortunes = [
  "大吉!今天是你的幸運日!🍀",
  "中吉!保持積極心態!😊", 
  "小吉!會有小驚喜等著你!✨",
  "平!平平淡淡也是福!😌",
  "凶!小心謹慎,避免衝動!⚠"
]

# 隨機幸運數字
lucky_number = random.randint(1, 99)

# 隨機幸運顏色
lucky_colors = ["紅色", "藍色", "綠色", "黃色", "紫色", "粉色"]
lucky_color = random.choice(lucky_colors)

print(f"\n{name},您今日的運勢是:")
print(random.choice(fortunes))
print(f"幸運數字:{lucky_number}")
print(f"幸運顏色:{lucky_color}")

🎮 互動遊戲:猜數字進階版

import random

print("🎯 猜數字遊戲 🎯")
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7

print("我想了一個1到100的數字,你能猜到嗎?")
print(f"你有{max_attempts}次機會!")

while attempts < max_attempts:
  guess = int(input(f"第{attempts + 1}次猜測:"))
  attempts += 1
  
  if guess == secret_number:
    print(f"🎉 太棒了!你猜對了!答案就是{secret_number}")
    print(f"你總共猜了{attempts}次!")
    break
  elif guess > secret_number:
    print("📉 太大了!再試試看!")
  else:
    print("📈 太小了!再試試看!")
  
  remaining = max_attempts - attempts
  if remaining > 0:
    print(f"還有{remaining}次機會!")
  else:
    print(f"😭 遊戲結束!答案是{secret_number}")

🤖 智慧選擇器實作 - 今天吃什麼決策器

import random

print("🍽 === 智慧選擇器:今天吃什麼? ===")
mood = input("你今天心情如何?(開心/難過/普通):")
budget = int(input("預算多少錢?"))

if mood == "開心" and budget >= 500:
    foods = ["高級日料", "法式餐廳", "牛排館"]
elif mood == "開心" and budget < 500:
    foods = ["火鍋", "燒烤", "義大利麵"]
elif mood == "難過":
    foods = ["泡麵", "冰淇淋", "炸雞"]
else:
    foods = ["便當", "麵店", "自助餐"]

choice = random.choice(foods)
print(f"🎯 建議你今天吃:{choice}")

if budget >= 300:
    print("💰 預算充足,好好享受吧!")
else:
    print("💡 省錢也能吃得開心!")

本週總結 🎉

🏆 今天我們學會了:

  • ✅ 條件判斷: if-else讓程式會思考
  • ✅ 比較運算: 六種符號判斷大小關係
  • ✅ 邏輯運算: and、or、not組合複雜條件
  • ✅ 多重判斷: elif處理多種情況
  • ✅ 互動選單: 打造使用者友善介面
  • ✅ 隨機功能: random模組增加趣味性
  • ✅ 演算法思維: 問題分解與條件設計

🎯 下週預告

下週我們將學習迴圈控制,讓程式能夠重複執行,處理大量資料!

作業:智慧生活助手系統 🤖

作業要求:

🎯 三選一作業 (下個主題二擇一)

  • 任選其一完成即可,選哪個不影響分數

📝 選項一:基礎練習 (適合初學者)

學生成績管理系統

  • 使用條件判斷製作成績分析與建議系統
  • 功能包含:
    • 多科成績輸入
    • 根據總分給出等級評價
    • 學習建議(可自訂)
  • 使用if-elif-else結構
  • 包含至少5種不同的成績等級

🔧 選項二:進階應用 (有點挑戰性)

智慧選擇決策系統

  • 整合多種功能選單:
    • 今天吃什麼建議器
    • 穿衣搭配建議器
    • 休閒活動推薦器
  • 結合random模組增加隨機性
  • 根據使用者輸入(心情、預算、天氣)給建議
  • 包含錯誤處理和重複選單功能

🚀 選項三:創意發揮 (自由度高)

個人化智慧助手

  • 主題:運用流程控制設計實用工具
  • 可能方向:學習計畫制定器、理財建議系統、健康管理助手
  • 必須包含:多重條件判斷、邏輯運算、互動選單
  • 鼓勵加入創新功能和美化GUI介面
  • 可結合之前學過的變數、資料型態等概念

-----------------------------------------

圖片放大特效

table樣式

準備好讓你的程式擁有「大腦」了嗎?

```python print("=== 📚 學生成績管理系統 ===") # 輸入成績 chinese = int(input("請輸入國文成績:")) english = int(input("請輸入英文成績:")) math = int(input("請輸入數學成績:")) # 計算總分和平均 total = chinese + english + math average = total / 3 print(f"總分:{total}") print(f"平均:{average:.1f}") # 成績等級判斷 if average >= 90: print("🏆 A級:優秀!") print("建議:保持優異表現!") elif average >= 80: print("👍 B級:良好!") print("建議:再加把勁衝A級!") elif average >= 70: print("✅ C級:及格!") print("建議:加強複習弱科!") elif average >= 60: print("⚠️ D級:待加強!") print("建議:需要密集複習!") else: print("💪 E級:需努力!") print("建議:尋求老師協助!") ```

### Random模組簡介

--- ## 💡 小練習:電影推薦系統 ### 任務說明 設計一個智慧電影推薦系統,根據使用者的喜好和時間給出推薦 ### 程式架構提示 ```python # 1. 輸入使用者喜好 genre = input("你喜歡什麼類型的電影?(動作/愛情/喜劇/科幻):") time = int(input("你有多少時間看電影?(分鐘):")) # 2. 根據類型和時間推薦 if genre == "動作" and time >= 120: print("推薦:復仇者聯盟系列") elif genre == "動作" and time < 120: print("推薦:玩命關頭系列") # 繼續完成其他條件... ``` ### 挑戰加分項 - 加入心情因素考量 - 根據年齡推薦適合電影 - 結合random模組隨機推薦

--- ## 🎓 運算思維:演算法設計 ### 問題分解步驟 1. **🎯 確定目標**:程式要解決什麼問題? 2. **📋 列出條件**:需要判斷哪些情況? 3. **🔄 設計流程**:條件的判斷順序 4. **✅ 測試驗證**:各種情況都考慮到了嗎? ### 條件設計原則 - **互斥性**:條件不能重複 - **完整性**:所有情況都要涵蓋 - **邏輯性**:判斷順序要合理 - **可讀性**:程式碼要清楚易懂 ### 🧩 思考練習 設計一個「穿衣建議系統」: - 考慮溫度、天氣、場合 - 給出適當的穿搭建議

準備好讓程式變得更強大了嗎?🚀