# try... except ###### tags: `python` try ...except為了要嘗試一切,排除了異常情況,並將這例外用except將錯誤集中處理 假設(此情況能行)排除(不能執行的例外) try 執行任務的程式碼 except: 當執行任務的程式碼中有錯誤訊息,就傳到這裡解決 EX: Q1:計算每次跑10公里所需時間 ```python=3.7 def run_timing(): n=0 sum_time=0.0 while True: spend_time=input("輸入時間") if spend_time=='': break try: spend_time=float(spend_time) sum_time+=spend_time n+=1 except Exception as e: print(e) if n>0: aver_time=float(sum_time/n) else: aver_time=0.0 print("跑",n,"次,總共花",aver_time) ``` 範例來自《python刷題訓練班》 資料來源http://c.biancheng.net/view/2315.html