避免错误
在视频中,您看到了几种可用于自定义函数的错误处理方法。
在本练习中,您将尝试其中一种做法:在出现错误时不抛出异常,而是打印一条有用的信息,同时不终止脚本。
本练习是课程的一部分
Python 中级:面向开发者
练习说明
- 使用一个关键字,尝试运行清理
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)