開始使用免費開始

避免錯誤

在影片中,你看到了幾種可套用在自訂函式上的錯誤處理做法。

在本練習中,你將試試其中一種做法:避免拋出錯誤;如果發生錯誤就印出有用的訊息,但不會終止腳本。

本練習屬於課程

Intermediate Python for Developers

檢視課程

練習說明

  • 使用一個關鍵字,讓你嘗試執行清理 text 的程式碼。
  • 再使用另一個關鍵字,當呼叫 clean_text() 函式發生錯誤時,印出有幫助的訊息。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def clean_text(text):
  # Attempt to clean the text
  ____:
    return text.replace(" ", "_").lower()
  # Run this code if an error occurs
  ____:
    print("The clean_text() function expects a string as an argument, please check the data type provided!")
    
clean_text(187)
編輯並執行程式碼