回傳多個值的函式
在前一個練習中,你建立了 tuple、將 tuple 指派給變數,並且進行了解包。這裡你會用 tuple 從函式回傳多個值。現在來更新 shout() 函式,讓它回傳多個值。不再只回傳一個字串,而是回傳兩個字串,且都會把字串 !!! 串接在後面。
注意,return x, y 和 return (x, y) 的結果相同:前者其實是把 x 和 y 在底層打包成一個 tuple!
本練習屬於課程
Python 函式入門
練習說明
- 修改函式標頭,將函式名稱改為
shout_all,並依序接受兩個參數word1與word2。 - 將字串
'!!!'分別串接到word1與word2後方,並分別指派給shout1與shout2。 - 建立一個由
shout1和shout2組成的 tupleshout_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)