函式、內建函式 functions, built-in functions


在 Python 裡,已經有不少寫好的 function,可以使用。 例如,我們最常使用到的 built-in functions 的 print( ) function。

自己定義的函式 defining functions + 呼叫函式 calling functions


為什麼需要用到,自己定義的函式呢? 如果你的code,有一部份是高重複性的動作,例如,機器人的步行與方向。 你需要一直重複這些coding,即使複製貼上,也是一件很累人的事情,也不易維護。 這個時候,把這些高重複性的code放進,自己定義的函式,就可以減省coding與維護方便。

語法與使用方式,如下。

def my_function():
    #Do this
    #Then do this
    #Finally do this

my_function()

Coding


def Laurence():
    print("1st")
    print("2nd")
    print("3rd")

Laurence()
a = "123"
b = 123
c = 1.23
d = True

def Laurence(a, b, c, d):
    print(a)
    print(type(a))
    print(b)
    print(type(b))
    print(c)
    print(type(c))
    print(d)
    print(type(d))
    
Laurence(a, b, c, d)

Console


1st
2nd
3rd