def check_number(num):
    if num < 0:
        print("數字不能為負數")
        return  # 提前終止函式的執行, 
        #return None #同效果
    elif num == 0:
        print("數字為零")
        return  # 提前終止函式的執行, 
        #return None #同效果
    
    print("數字為正數")
    # 在此處可以繼續執行其他程式碼
# 測試函式
check_number(10)  # 輸出: 數字為正數
check_number(-5)  # 輸出: 數字不能為負數
check_number(0)   # 輸出: 數字為零輸出結果:

code:
def process_data(data):
    try:
        assert len(data) > 0, "資料不能為空"
    except AssertionError as e:
        print("捕捉到 AssertionError:", e)
        return  # 提前終止函式的執行
    
    # 在此處可以繼續處理資料的程式碼
    print("處理資料:", data)
# 測試函式
process_data([1, 2, 3, 4])  # 輸出: 處理資料: [1, 2, 3, 4]
process_data([])           # 輸出: 捕捉到 AssertionError: 資料不能為空輸出結果:

實際應用:

GUI2:

上圖的GUI介面,
第0 row的左右為兩個Listbox
變數以字典,巢狀字典儲存
字典的key不能重複,
若選擇的項目已經在右邊的Listbox
添加重複的項目需觸發AssertionError
並且提前終止函式
部分程式碼:

assert cable_name not in selected_cables, \
“此cable已經在’已選擇’box中,請勿重複選擇相同的線”
斷言失敗,觸發AssertionError的話
就需要return終止函式
不然重複的線仍會被加到右邊的Listbox

嘗試添加相同的線到右邊的Listbox,
AssertionError被傳遞到下方的Text,
且無法添加
推薦hahow線上學習python: https://igrape.net/30afN
![Python Logging 完全指南:從基礎到實戰應用; import logging ; logging.basicConfig(level=logging.INFO, handlers=[ logging.StreamHandler(), logging.FileHandler(‘app.log’, mode=’a’, encoding=’utf-8′)] ) ; inspect.currentframe().f_code.co_name #動態取得funcName Python Logging 完全指南:從基礎到實戰應用; import logging ; logging.basicConfig(level=logging.INFO, handlers=[ logging.StreamHandler(), logging.FileHandler(‘app.log’, mode=’a’, encoding=’utf-8′)] ) ; inspect.currentframe().f_code.co_name #動態取得funcName](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2025/10/20251021155823_0_c16012.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


![Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2025/07/20250716084059_0_c5b368.png?quality=90&zoom=2&ssl=1&resize=350%2C233)






近期留言