攝影或3C

Python 進階心法:告別 Else,讓程式碼「平」易近人

在 Python 開發中,你是否曾發現程式碼不知不覺變成了「箭頭」形狀?
層層疊疊的 if-else 與縮排,不僅讓程式碼難以閱讀,更增加了維護的認知負擔。

其實,透過 「隱含 Else」 (Implicit Else) 的思維,
利用 return, continue, break 甚至邏輯運算子,我們可以把邏輯「攤平」。
這不是要你永遠不用 else,
而是要你學會「儘早處理異常,讓核心邏輯留在最外層」

以下是五種常見的重構模式:

  1. 提早返回 (Early Return)
    這是最經典的衛語句 (Guard Clause) 模式。把函數開頭視為「安檢門」,不合規定的直接請回,核心邏輯不需要包在 else 裡。

❌ 巢狀地獄 (Nested)

def update_user_profile(user, data):
    if user is not None:
        if user.is_active:
            if data:
                user.update(data)
                user.save()
            else:
                print("沒有資料可更新")
        else:
            print("帳號未啟用")
    else:
        print("使用者不存在")

✅ 隱含 Else (Flat)

def update_user_profile(user, data):
    # 1. 檢查存在性 (隱含 Else: user 存在)
    if user is None:
        print("使用者不存在")
        return

    # 2. 檢查狀態 (隱含 Else: user  active )
    if not user.is_active:
        print("帳號未啟用")
        return

    # 3. 檢查資料 (隱含 Else: data 有內容)
    if not data:
        print("沒有資料可更新")
        return

    # 4. 核心邏輯 (完全平展無縮排)
    user.update(data)
    user.save()

2. 迴圈中的過濾 (Continue)

在迴圈中,遇到不感興趣無效的項目,直接用 continue 跳過。
這讓你永遠專注於「當下要處理的那個項目」,而不是把它包在 if 裡。

❌ 傳統寫法

for file_name in file_list:
    if file_name.endswith(".txt"):
        # 這裡縮排變深了如果是複雜邏輯會很難讀
        content = read_file(file_name)
        print(f"Processing {file_name}: {len(content)} bytes")

✅ 隱含 Else 寫法

for file_name in file_list:
    # 過濾條件 (隱含 Else: 這是我們要的 .txt )
    if not file_name.endswith(".txt"):
        continue 
    
    # 核心邏輯直接寫在迴圈的第一層
    content = read_file(file_name)
    print(f"Processing {file_name}: {len(content)} bytes")

3. 搜索與中斷 (Break)

當你在尋找某個東西,或是遇到「致命錯誤」不想再繼續跑迴圈時,break 不僅是停止,也隱含了「之後的迭代都不用做了」。

❌ 傳統標記法

target_found = False
for item in items:
    if not target_found:
        if item.id == target_id:
            target_found = True
            print("找到了!")
            # 這裡之後可能還會空轉迴圈

✅ 隱含 Else 寫法

for item in items:
    if item.id == target_id:
        print("找到了!")
        break  # 任務結束直接跳出
    
    # (隱含 Else: 目前這個 item 不是目標繼續找下一個)

4. 異常用於防禦 (Raise)

這比 return 更強烈。如果不符合條件直接報錯,程式碼甚至不需要往下看 return 什麼。

❌ 傳統寫法

def connect_to_server(config):
    if config.get('host'):
        connect(config['host'])
    else:
        raise ValueError("缺少 host 設定")

✅ 隱含 Else 寫法

def connect_to_server(config):
    # 先把錯誤丟出去 (隱含 Else: host 設定是存在的)
    if not config.get('host'):
        raise ValueError("缺少 host 設定")
    
    connect(config['host'])

5. 極致簡潔:Pythonic 的單行隱含 Else

Python 有許多語法糖,其實也就是「隱含 Else」的極致展現。

A. 預設值賦予 (or)

利用 or 的短路特性,如果前面是空值,就取後面的預設值。

# ❌ Explicit
if config_port:
    port = config_port
else:
    port = 8080

# ✅ Implicit (如果 config_port  None/0/Empty就用 8080)
port = config_port or 8080

C. 字典安全取值 (dict.get)

最優雅的取值方式,完全不需要寫 if key in dict。

data = {"name": "Alice"}

# ❌ Explicit
if "age" in data:
    age = data["age"]
else:
    age = 18

# ✅ Implicit (如果 'age' 不存在就回傳 18)
age = data.get("age", 18)

總結

寫程式就像寫文章。「隱含 Else」 的精隨在於:

  1. 先處理雜訊(錯誤檢查、過濾無效資料)。
  2. 儘早離開(return, continue, break, raise)。
  3. 讓重點浮現(核心邏輯不需要縮排)。

下次當你發現手指一直按 Tab 鍵縮排時,停下來想一想:「我能不能先處理這個 else 情況,然後轉身離開?」

推薦hahow線上學習python: https://igrape.net/30afN

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡