開始使用免費開始

回傳多個值的函式

在前一個練習中,你建立了 tuple、將 tuple 指派給變數,並且進行了解包。這裡你會用 tuple 從函式回傳多個值。現在來更新 shout() 函式,讓它回傳多個值。不再只回傳一個字串,而是回傳兩個字串,且都會把字串 !!! 串接在後面。

注意,return x, yreturn (x, y) 的結果相同:前者其實是把 xy 在底層打包成一個 tuple!

本練習屬於課程

Python 函式入門

檢視課程

練習說明

  • 修改函式標頭,將函式名稱改為 shout_all,並依序接受兩個參數 word1word2
  • 將字串 '!!!' 分別串接到 word1word2 後方,並分別指派給 shout1shout2
  • 建立一個由 shout1shout2 組成的 tuple 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)
編輯並執行程式碼