开始使用免费开始使用

带有多个默认参数的函数

您已经定义了一个带默认参数的函数——还可以更进一步!现在请尝试定义一个包含多个默认参数的函数,并以多种方式调用它。

定义函数后,先在调用时为函数的所有默认参数都提供取值。此外,也尝试在调用时不给其中一个默认参数传值——看看这会如何改变函数的输出!

本练习是课程的一部分

Python 函数入门

查看课程

练习说明

  • 完成函数头,函数名为 shout_echo。按顺序接收参数:位置参数 word1,默认参数 echo(默认值为 1),默认参数 intense(默认值为 False)。
  • if 语句体内,对字符串对象 echo_word 调用 .upper() 方法,将其转换为大写。
  • 调用 shout_echo(),传入字符串 "Hey"echo 的值 5intense 的值 True。将结果赋给 with_big_echo
  • 调用 shout_echo(),传入字符串 "Hey"intense 的值 True。将结果赋给 big_no_echo

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Define shout_echo
def ____(____, ____, ____):
    """Concatenate echo copies of word1 and three
    exclamation marks at the end of the string."""

    # Concatenate echo copies of word1 using *: echo_word
    echo_word = word1 * echo

    # Make echo_word uppercase if intense is True
    if intense is True:
        # Make uppercase and concatenate '!!!': echo_word_new
        echo_word_new = ____ + '!!!'
    else:
        # Concatenate '!!!' to echo_word: echo_word_new
        echo_word_new = echo_word + '!!!'

    # Return echo_word_new
    return echo_word_new

# Call shout_echo() with "Hey", echo=5 and intense=True: with_big_echo
with_big_echo = ____

# Call shout_echo() with "Hey" and intense=True: big_no_echo
big_no_echo = ____

# Print values
print(with_big_echo)
print(big_no_echo)
编辑并运行代码