Function 介紹(二):Function的括號裡面有沒有東西有差嗎?
括號裡面有什麼意義?
在前一篇介紹,我們簡單了解了什麼是 funtion,知道了可以把一整段 code 打包起來重複用,那我們來看看我們做的 function 的括號有什麼差別吧。
在我們使用 function 的時候,通常會看到兩種寫法:
say_hello()
print(“hello”)
兩個功能我都希望結果是顯示出 hello,主要差異就是括號裡面有沒有東西~
首先要知道 () 是代表呼叫 function
第一個 say_hello() 括號裡面沒有東西,代表我們沒有傳任何資料或數據進去
第二個 print(“hello”) 括號裡面放了一個字串 “hello”,代表我們有把資料或數據傳進去我們的這個功能裡
也就是說,括號裡面其實就是我們要提供給 function 的原物料,然後 function 就會像一台機器,因應我們給的原物料來做出產品。
舉例來說:
def main():
say_hello()
say_what(“hello”)
def say_hello():
print(“Hello!”)
def say_what(string):
print(string)
就結果來說會顯示兩行 hello,但他們運作的方式差異很大
say_hello(),無論如何都只會印出 hello,但 say_waht(“hello”) 括號內的 hello 你可以改成任何你想講的話
所以括號內沒東西就是執行同一件事而已,但括號內有東西就代表執行時會因為不同的數據而獲得不同答案
總結:
() 是「呼叫 function」的符號,但裡面要不要放資料,取決於我們一開始設計 function 的時候,想不想讓使用者因資料不同而獲得不同結果。
-
- 沒有資料 say_hello():不管是誰、不管什麼時候都做固定一樣的事。
- 有資料 say_what(string):會因為使用者提供的資料不同而提供不同的結果。
Tips: 記得如果當初設計 function 時,括號裡有東西的時候,在使用的時候也一定要加入資料唷!不然就會直接獲得大大的Error!
stanCode標準程式教育機構-你也值得更好的教育
Facebook|https://www.facebook.com/stancode.tw
Instagram|https://www.instagram.com/stancode_tw/
YouTube|https://www.youtube.com/@stancode7228/videos
Website|https://www.stancode.tw/
TikTok|https://www.tiktok.com/@standardcoding
