回傳單一值的函式
你越來越上手了!再來嘗試修改 shout() 函式,讓它在函式內不要印出結果,而是改為「回傳」單一值。回想一下,return 關鍵字可以讓你從函式中回傳值。這裡提供你先前撰寫的 shout() 函式的一部分作為參考。一般來說,回傳值比直接列印更好,因為如同你先前所見,把 print() 呼叫指派給變數時,其型別會是 NoneType。
本練習屬於課程
Python 函式入門
練習說明
- 在函式主體中,將
word的字串與'!!!'串接,並指派給shout_word。 - 將
print()陳述式改成適當的return陳述式。 - 呼叫
shout()函式,傳入字串'congratulations',並把呼叫結果指派給變數yell。 - 為了檢查
yell是否包含shout()回傳的值,列印yell的值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define shout with the parameter, word
def shout(word):
"""Return a string with three exclamation marks"""
# Concatenate the strings: shout_word
# Replace print with return
print(shout_word)
# Pass 'congratulations' to shout: yell
# Print yell