開始使用免費開始

具有多個預設引數的函式

你已經定義了一個使用預設引數的函式——先別停下來!接著你要試著定義一個擁有多個預設引數的函式,並以不同方式呼叫這個函式。

定義好函式之後,你會透過提供該函式所有預設引數的值來呼叫它。除此之外,你也會在呼叫時不替其中一個預設引數提供值,看看這會如何改變函式的輸出!

本練習屬於課程

Python 函式入門

檢視課程

練習說明

  • 以函式名稱 shout_echo 完成函式標頭。依序接受引數 word1、預設引數 echo(預設值為 1),以及預設引數 intense(預設值為 False)。
  • if 敘述的主體裡,對字串物件 echo_word 套用 .upper() 方法,將其轉為大寫。
  • 以字串 "Hey"echo 的值 5,以及 intense 的值 True 呼叫 shout_echo()。將結果指定給 with_big_echo
  • 以字串 "Hey"intense 的值 True 呼叫 shout_echo()。將結果指定給 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)
編輯並執行程式碼