开始使用免费开始使用

返回错误

现在来试试另一种错误处理方法。

请修改 clean_text() 函数:当使用了不正确的数据类型时,故意抛出一个错误。

本练习是课程的一部分

Python 中级:面向开发者

查看课程

练习说明

  • 检查参数 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")
编辑并运行代码