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爬蟲:BeautifulSoup的 .find_all() 與 .find() 與 .select(‘標籤名[屬性名1=”屬性值1″][屬性名2=”屬性值2″]’) ; from bs4 import BeautifulSoup ; Live Server(可以預覽HTML的VS Code套件) Python爬蟲:BeautifulSoup的 .find_all() 與 .find() 與 .select(‘標籤名[屬性名1=”屬性值1″][屬性名2=”屬性值2″]’) ; from bs4 import BeautifulSoup ; Live Server(可以預覽HTML的VS Code套件)](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2025/03/20250330190318_0_925655.jpg?quality=90&zoom=2&ssl=1&resize=350%2C233)



![Python: 資料格式如 List[dict],如何快速將SN加入每一個dict中,以利Excel輸出?如何解包dict? **dict ; 將List[dict]的資料轉為pandas.DataFrame 長什麼樣子? Python: 資料格式如 List[dict],如何快速將SN加入每一個dict中,以利Excel輸出?如何解包dict? **dict ; 將List[dict]的資料轉為pandas.DataFrame 長什麼樣子?](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2024/02/20240208093926_0.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

![一文搞懂Python pandas.DataFrame去重:df.drop_duplicates() 與 df[~df.duplicated()] 的等價、差異與最佳實踐 一文搞懂Python pandas.DataFrame去重:df.drop_duplicates() 與 df[~df.duplicated()] 的等價、差異與最佳實踐](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2025/08/20250808202701_0_66f9bc.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



近期留言