複数のデフォルト引数を持つ関数
デフォルト引数を使う関数を定義できましたね。ここで止まらず、デフォルト引数を複数持つ関数を定義し、さまざまな方法で呼び出してみましょう。
関数を定義したら、関数のデフォルト引数に対して値をすべて指定して呼び出します。さらに、あるデフォルト引数には値を渡さずに呼び出して、出力がどう変わるかを確認します。
この演習はコースの一部です
Pythonの関数入門
演習の手順
- 関数名を
shout_echoとして関数ヘッダーを完成させます。引数は順に、通常の引数word1、デフォルト値が1のデフォルト引数echo、デフォルト値がFalseのデフォルト引数intenseを受け取ります。 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)