## 第五章:函式 ### **基本函式定義和調用** - **定義函式**:使用 `def` 關鍵字定義函式。 ```python def greet(name): return f"Hello, {name}!" # f 是因為會回傳變數 ``` - **調用函式**:通過函式名和參數調用函式。 ```python print(greet("Alice")) # 輸出: Hello, Alice! ``` - **默認參數值**:可以為參數設置默認值。 ```python def greet(name="World"): return f"Hello, {name}!" print(greet()) # 輸出: Hello, World! print(greet("Bob")) # 輸出: Hello, Bob! ``` - **返回值**:函式可以返回一個值,使用 `return` 關鍵字。 ```python def add(a, b): return a + b result = add(3, 5) print(result) # 輸出: 8 ``` - **函數作為參數**:將函式本身作為參數傳入其他函式中 ```python= def firstName(name): return name.split()[0] def firstNameForChinese(name): return name[1] + name[2] def greet(name, getfirstName): return f'Hello, {getfirstName(name)}!' print(greet('John Cena', firstName)) print(greet('張忠謀', firstNameForChinese)) ``` - **變數範圍** - 區分:Python 中變數可分為「全域變數(global)」與「區域變數(local)」。 - 區域變數:在函式內部定義,僅在該函式中有效。 ```python= def my_func(): x = 10 # x 是區域變數 print(x) my_func() print(x) # 會錯誤:x is not defined ``` - 全域變數:在函式外部定義,可以在多個函式中被讀取(但要修改必須使用 global)。 ```python= def my_func(): global x # x 改為全域變數 x = 10 print(x) my_func() print(x) # 可以正常顯示 x ``` :::spoiler 作業:寫一個函式判斷是不是質數 ```python= def isPrime(n): for i in range(2, n//2): if n % i == 0: return False return True print(isPrime(13)) print(isPrime(15)) ``` :::