嵌套函数 I
您在上一段视频中学习了如何在函数内部再定义函数。这样做的一个原因是避免在不同函数中重复编写相同的计算。定义嵌套函数本身并不新奇:像定义普通函数一样使用 def,然后把它写在另一个函数内部即可!
在本练习中,您将于函数 three_shouts() 内部定义一个嵌套函数 inner(),用于把字符串对象与 !!! 连接。three_shouts() 随后返回一个包含 3 个元素的元组;每个元素都是通过 inner() 将字符串与 !!! 拼接后的结果。开始动手吧!
本练习是课程的一部分
Python 函数入门
练习说明
- 补全嵌套函数的函数头,函数名为
inner(),且仅包含一个参数word。 - 补全返回值:元组中的每个元素都应为一次对
inner()的调用,并将three_shouts()的各个参数分别作为每次调用的实参。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define three_shouts
def three_shouts(word1, word2, word3):
"""Returns a tuple of strings
concatenated with '!!!'."""
# Define inner
def ____(____):
"""Returns a string concatenated with '!!!'."""
return word + '!!!'
# Return a tuple of strings
return (____, ____, ____)
# Call three_shouts() and print
print(three_shouts('a', 'b', 'c'))