為什麼要用 return?
前兩篇我們介紹了 function 的基本概念、還有括號裡有沒有東西的差異,今天來看看很重要的 return 吧!
在討論 function 的時候,最常見的問題,就是我明明就把結過 print 出來了,為什麼我還要 return?
這就要先來看看 print() 跟 return 的差別了,
以製作一個加總數字的 function 來看:
def add(a,b): print(a+b)
假設執行 add(2,6),我們也是可以直接 print 出答案 8 的,但如果今天我們需要用到這個加總後的結果,裝到箱子裡面的東西,就會是空的!
def main(): ans = add(2,6) print(ans)
這個時候執行出來的結果就會是 8 跟 None!因為我們的 add 只有 print 的功能,並沒有丟東西回去給我們的使用者,所以後面 ans 的結果是什麼都沒有~所以如果我們需要使用到結果的時候,就要透過 return 來讓使用者知道答案了!
def add(a,b): return a+b
此時執行出來就會是 main 裡面的 8 了!雖然都是印出 8 的結果,但調整後的結果,不只是單純印出一個答案,而是把資料好好的存下來,然後也就可以在別的 function 裡面使用,讓我們的使用上更多元了。
總結:
stanCode標準程式教育機構-你也值得更好的教育
Facebook|https://www.facebook.com/stancode.twInstagram|https://www.instagram.com/stancode_tw/YouTube|https://www.youtube.com/@stancode7228/videosWebsite|https://www.stancode.tw/TikTok|https://www.tiktok.com/@standardcoding