複数の値を返す関数
前の演習では、タプルの作成、変数への代入、アンパックを行いました。ここではタプルを使って、関数から複数の値を返します。shout() 関数を更新して複数の値を返すようにしましょう。1 つの文字列だけを返す代わりに、各文字列に !!! を連結した 2 つの文字列を返します。
return x, y は return (x, y) と同じ結果になる点に注意してください。前者は内部的に x と y をタプルにパックしています。
この演習はコースの一部です
Pythonの関数入門
演習の手順
- 関数ヘッダーを修正し、関数名を
shout_allにして、順にword1とword2の 2 つのパラメーターを受け取るようにします。 - 文字列
'!!!'をword1とword2のそれぞれに連結し、shout1とshout2に代入します。 shout1とshout2からなるタプルshout_wordsを作成します。- 文字列
'congratulations'と'you'を引数にしてshout_all()を呼び出し、結果をyell1とyell2に代入します(shout_all()は 2 つの値を返すことを忘れないでください)。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Define shout_all with parameters word1 and word2
def shout_all(____, ____):
"""Return a tuple of strings"""
# Concatenate word1 with '!!!': shout1
# Concatenate word2 with '!!!': shout2
# Construct a tuple with shout1 and shout2: shout_words
# Return shout_words
return shout_words
# Pass 'congratulations' and 'you' to shout_all(): yell1, yell2
# Print yell1 and yell2
print(yell1)
print(yell2)