開始使用免費開始

回傳錯誤

來試試另一種錯誤處理方式。

請修改 clean_text() 函式,當使用了不正確的資料型別時,刻意產生一個錯誤。

本練習屬於課程

Intermediate Python for Developers

檢視課程

練習說明

  • 檢查 text 參數的資料型別是否為字串 str
  • else 區塊中產生 TypeError(),以防止腳本繼續執行,並回傳具體的說明訊息。

動手互動練習

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

def clean_text(text):
  # Check the data type
  if ____(text) == ____:
    return text.replace(" ", "_").lower()
  else:
    # Return a TypeError error if the wrong data type was used
    ____ ____("The clean_text() function expects a string as an argument, please check the data type provided!")
    
clean_text("User Name 187")
編輯並執行程式碼