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
]*>.*?底下插入一個圖檔.*?</w:p>’, flags = re.DOTALL) ; new_xml, n = pattern.subn(”, xml, count=1)' title='Python正則替換:全面掌握 re.sub 與 re.subn 的差異與實戰 #substitute(替換); . 預設匹配「除\n以外的任意單一字元」; pattern = re.compile(r'<w:p[^>]*>.*?底下插入一個圖檔.*?</w:p>’, flags = re.DOTALL) ; new_xml, n = pattern.subn(”, xml, count=1)' loading='lazy' width=350 height=233 />
![Python: pandas.read_excel(r”路徑\檔名.副檔名”, header = None), 自動加上0,1…的欄標籤, DataFrame如何取某一直欄或橫列? 如何用 .iloc[bool_list] 取出判斷式為真的那一列? bool_list = list( df[0] == 0 ) ; bool_list = list(df[0].isin([0])) ; DataFrame如何顯示完整的資料? pandas.set_option ( “display.max_rows”, None) Python: pandas.read_excel(r”路徑\檔名.副檔名”, header = None), 自動加上0,1…的欄標籤, DataFrame如何取某一直欄或橫列? 如何用 .iloc[bool_list] 取出判斷式為真的那一列? bool_list = list( df[0] == 0 ) ; bool_list = list(df[0].isin([0])) ; DataFrame如何顯示完整的資料? pandas.set_option ( “display.max_rows”, None)](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2022/11/20221128164005_44.png?quality=90&zoom=2&ssl=1&resize=350%2C233)




![Python TQC考題404 數字反轉判斷,n_rev=n[::-1], list1.reverse() Python TQC考題404 數字反轉判斷,n_rev=n[::-1], list1.reverse()](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2022/04/20220825152414_97.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


近期留言