巢狀條件

在 if 裡面可以再放 if,處理更複雜的邏輯。

基本語法

age = 25
has_id = True

if age >= 18:
    if has_id:
        print("可以進入")
    else:
        print("請出示證件")
else:
    print("未成年不可進入")

可以用 and 簡化

# 巢狀寫法
if age >= 18:
    if has_id:
        print("可以進入")

# and 寫法(更簡潔)
if age >= 18 and has_id:
    print("可以進入")

多層巢狀

score = 85
attendance = 90

if score >= 60:
    if attendance >= 80:
        if score >= 90:
            print("優秀表現!")
        else:
            print("表現良好")
    else:
        print("出席率不足")
else:
    print("成績不及格")

建議:避免過深巢狀

# 使用提早返回或 and/or 簡化
def check_permission(age, has_id, is_member):
    if age < 18:
        return "未成年"
    if not has_id:
        return "無證件"
    if not is_member:
        return "非會員"
    return "歡迎光臨"

練習

判斷一個年份是否為閏年(需要巢狀判斷)

💻 程式碼編輯器
📤 執行結果
等待執行...
← 上一課 下一課 →