使用 try-except 进行错误处理
编写自定义函数的一个好习惯,是预判他人(或您自己在误用函数时)可能会如何使用您定义的函数。
正如在上一个练习中所见,len() 函数能处理字符串、列表和元组等输入参数,但不能处理 int 类型。遇到无效输入参数时会抛出相应的错误及错误信息。实现这一点的一种方式是使用 try-except 进行异常处理。
在本练习中,您将定义一个函数,并使用 try-except 代码块来处理向函数传入不正确的输入参数的情形。
回忆您在之前练习中定义的 shout_echo() 函数;示例代码中已提供了部分函数定义。您的目标是补全函数定义中的异常处理代码,并在抛出错误时提供合适的错误信息。
本练习是课程的一部分
Python 函数入门
练习说明
- 将变量
echo_word和shout_words初始化为空字符串。 - 在异常处理代码块的合适位置添加关键字
try和except。 - 使用
*运算符将word1重复echo次并连接。将结果赋给echo_word。 - 将字符串
'!!!'连接到echo_word之后。将结果赋给shout_words。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define shout_echo
def shout_echo(word1, echo=1):
"""Concatenate echo copies of word1 and three
exclamation marks at the end of the string."""
# Initialize empty strings: echo_word, shout_words
# Add exception handling with try-except
____:
# Concatenate echo copies of word1 using *: echo_word
echo_word = ____
# Concatenate '!!!' to echo_word: shout_words
shout_words = ____
____:
# Print error message
print("word1 must be a string and echo must be an integer.")
# Return shout_words
return shout_words
# Call shout_echo
shout_echo("particle", echo="accelerator")