始める無料で始める

複数の値を返す関数

前の演習では、タプルの作成、変数への代入、アンパックを行いました。ここではタプルを使って、関数から複数の値を返します。shout() 関数を更新して複数の値を返すようにしましょう。1 つの文字列だけを返す代わりに、各文字列に !!! を連結した 2 つの文字列を返します。

return x, yreturn (x, y) と同じ結果になる点に注意してください。前者は内部的に xy をタプルにパックしています。

この演習はコースの一部です

Pythonの関数入門

コースを見る

演習の手順

  • 関数ヘッダーを修正し、関数名を shout_all にして、順に word1word2 の 2 つのパラメーターを受け取るようにします。
  • 文字列 '!!!'word1word2 のそれぞれに連結し、shout1shout2 に代入します。
  • shout1shout2 からなるタプル shout_words を作成します。
  • 文字列 'congratulations''you' を引数にして shout_all() を呼び出し、結果を yell1yell2 に代入します(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)
コードを編集して実行