具有多個預設引數的函式
你已經定義了一個使用預設引數的函式——先別停下來!接著你要試著定義一個擁有多個預設引數的函式,並以不同方式呼叫這個函式。
定義好函式之後,你會透過提供該函式所有預設引數的值來呼叫它。除此之外,你也會在呼叫時不替其中一個預設引數提供值,看看這會如何改變函式的輸出!
本練習屬於課程
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)