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 TQC考題810 最大值與最小值之差,L=[eval(i) for i in s.split()] Python TQC考題810 最大值與最小值之差,L=[eval(i) for i in s.split()]](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2022/05/20220507094526_36.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



![Python-docx 圖片提取完全指南:從 rId 到二進位資料的探險rid ; part = doc.part.rels[rid].target_part #return part.blob if “ImagePart” in type(part).__name__ else None Python-docx 圖片提取完全指南:從 rId 到二進位資料的探險rid ; part = doc.part.rels[rid].target_part #return part.blob if “ImagePart” in type(part).__name__ else None](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2026/01/20260113135812_0_8fa645.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![使用 Python 檢驗字符串格式:掌握正則表達式(Regular Expression)的起始^與終止$符號, pattern = r’^GATR[0-9]{4}$’ 使用 Python 檢驗字符串格式:掌握正則表達式(Regular Expression)的起始^與終止$符號, pattern = r’^GATR[0-9]{4}$’](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2024/07/20240712093637_0.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

![Python 進階技巧:海象運算子 (Walrus Operator) 實戰教學 [w_clean for w in words if (w_clean:=w.lower().strip()) and w_clean not in STOPWORDS] Python 進階技巧:海象運算子 (Walrus Operator) 實戰教學 [w_clean for w in words if (w_clean:=w.lower().strip()) and w_clean not in STOPWORDS]](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2026/02/20260210083748_0_a7d9bf.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

近期留言