# 資研 3/29 社課講義
[**提問表單**](https://forms.gle/z4dPC1JPV6uA2q9w7)
---
## 函式 Functions
- 分為 **內建函式** 和 **自訂函式**
### 內建函式
像是之前學的`print()`、`input()`、`len()`、`int()`...,都是 **Python** 的內建函式
### 自訂函式
:::warning
**使用時機**:當一個較為複雜的步驟需要 <Font color='#AE0000'>**反覆執行**</Font> 時,利用自訂函示來簡化程式碼
:::
**寫法**:
```python=
def function_name(variables):
# Function action
return value
```
**例子**:
```python=
def Cubed(x):
return x**3
```
>記得要縮排、加冒號
#### 傳入變數的比較
1. 不傳入變數
```python=
def greeting():
print('Hello!')
return 'world'
```
:::info
Q:比較在函式中 `print` 和 `return` 有什麼差別?
:::
2. 傳入多個變數(固定數量)
```python=
def age(child_a, child_b):
print(str(child_a), str(child_b), sep='\n')
```
>變數會依傳入順序相對應
:::warning
- 當呼喚函式時,事先指定變數,則已指定之變數順序為優先
- 當制定函式時,先指定變數之值,若呼喚函式時,未傳入變數,則依函式變數為主
:::
3. 傳入多個變數(數量未知)
**使用一個`*`時,所傳入的變數們類似一個列表**
```python=
def grade(*class_201):
return class_201[2]
```
**使用兩個`*`時,所傳入的變數們類似於一個字典**
```python=
def personal_grade(**Subject):
return Subject['History']
```
### 練習
請利用以下資料,利用函式寫一個程式幫老師算出各位同學的最高成績
>資料格式:*座號 成績1 成績2 成績3*
:::spoiler 資料
```
[[1, 58, 19, 7],
[2, 50, 24, 80],
[3, 81, 100, 58],
[4, 52, 71, 2],
[5, 62, 82, 86],
[6, 31, 48, 52],
[7, 21, 16, 3],
[8, 2, 13, 77],
[9, 11, 78, 32],
[10, 95, 12, 89],
[11, 39, 82, 66],
[12, 11, 56, 93],
[13, 27, 21, 23],
[14, 87, 70, 56],
[15, 49, 15, 64],
[16, 9, 96, 15],
[17, 45, 85, 24],
[18, 27, 68, 49],
[19, 59, 7, 61],
[20, 86, 72, 62],
[21, 53, 77, 24],
[22, 77, 29, 4],
[23, 9, 23, 98],
[24, 72, 52, 14],
[25, 65, 35, 82],
[26, 59, 31, 88],
[27, 73, 75, 28],
[28, 1, 37, 50],
[29, 69, 98, 67],
[30, 8, 47, 50],
[31, 32, 67, 34],
[32, 55, 40, 3],
[33, 45, 22, 11]]
```
:::
程式碼
```python=
def find_maximum(*grade):
m = max(grade[0], grade[1], grade[2])
return m
for i in grade:
print(i[0], find_maximum(i[1], i[2], i[3]))
```
## 遞迴 Recursion

由前一個(或以上)的值以自相似方法重複過程來決定下一個值
>是一種[**時間複雜度**](https://medium.com/appworks-school/%E5%88%9D%E5%AD%B8%E8%80%85%E5%AD%B8%E6%BC%94%E7%AE%97%E6%B3%95-%E5%BE%9E%E6%99%82%E9%96%93%E8%A4%87%E9%9B%9C%E5%BA%A6%E8%AA%8D%E8%AD%98%E5%B8%B8%E8%A6%8B%E6%BC%94%E7%AE%97%E6%B3%95-%E4%B8%80-b46fece65ba5)很高的演算法(白話:很費時間跟效能)競賽盡量避免使用
**等差級數**
```python=
def f1(n):
if n == 1: return 1
return n + f1(n-1)
```
:::info
試試看利用遞迴寫出 **費波那契數列** 的函式
ex.1、1、2、3、5、8、13、21、34、55、89...(後一項為前2項之和)
```python=
def f(n):
if n == 1 or n == 2: return 1
return f(n-1) + f(n-2)
```
:::
---
## 補充資料
**推薦網站:**[**W3Schools**](https://www.w3schools.com/)