> 函式整理 & 字串整理
===
**作者 - 吳映柔
編輯 - BESTCI跨域人才程式能力培育計畫 / NTU BESA**
**項目**
==function
(stack frame & information hiding)==
==string concept==
**共筆內容**
# Function and String Concept
## 一、Function
### 1) 我們曾使用過的 function
###### ```move()```
###### ```print('c001')```
>在 <font color="#2C7AAC">**User 端**</font>,括弧裡面的是 <font color="#2C7AAC">**arguments**</font>,負責傳數值;在 <font color="#AC2C7A">**Coder 端**</font>,括弧裡面的是 <font color="#AC2C7A">**parameters**</font>,負責接數值。
###### ```guess = int (input('?'))```
>guess 是 return value
##### 建構 function 時重要的概念為 <font color="#2CAC9E">**information hiding**</font>,我們只需要知道要丟什麼東西進去、會丟什麼東西出來。目的是完全不用擔心程式碼是怎麼寫的,就像我們不會做果汁機,只要會使用 : )
### 2) Function 說明舉例 1:<font color="#2CAC9E">果汁機</font>
- 若果汁機本身是一個 function
- 果汁機的<font color="#AC2C7A">**使用規則**</font>,也就是 <font color="#AC2C7A">**Coder 端**</font>
```python=
def 果汁機(f,l)
```
- <font color="#2C7AAC">**User 端**</font>使用者做的事
```python=
紙杯 = 果汁機(香蕉, 巧克力牛奶)
```
##### 香蕉會傳到 Coder 端的 f,巧克力牛奶會傳到 Coder 端的 l。Coder 端果汁機有了 f、l,做完丟出 juice,User 端的紙杯接 juice。
### 3) Function 說明舉例 2:<font color="#2CAC9E">數字比大小</font>
- <font color="#2C7AAC">**User 端**</font>
```python=
def main():
ans=my_bigger(9,10) #10
ans=my_bigger(10,9) #10
ans=my_bigger(10,9) #10
```
- <font color="AC2C7A">**Coder 端**</font>
```python=
def my_bigger(n1,n2):
"""
:paran n1: int, the first value to be compared.
:paran n2: int, the second value to be compared.
使用三一律
"""
if n1 > n2:
return n1
if n2 > n1:
return n2
elif:
return n2
```
- <font color="AC2C7A">**Coder 端**</font>精簡版
```python=
if n1 > n2:
return n1
else:
return n2
```
- <font color="AC2C7A">**Coder 端**</font>更精簡版 - 若非 n1 > n2 就會到 no 區間 return n2,可以不必再用 else 表示
```python=
if n1 > n2:
return n1
return n2
```
- 輸入兩整數,回傳較小數值的程式
```python=
def main():
"""
Call my_min function
"""
n1 = int(input('First Number: '))
n2 = int(input('Second Number: '))
smaller = my_smaller(n1, n2)
print(smaller)
def my_smaller(n1, n2):
"""
:param n1: int, the number to be compared
:param n2: int, the number to be compared
:return: int, the smaller one between n1 and n2
"""
if n1 < n2:
return n1
return n2
```
### 4) Function 說明舉例 3:<font color="#2CAC9E">羅密歐與茱麗葉</font>
- 羅密歐與茱麗葉的悲劇 : (
```python=
def main():
Romeo = 4
look_for_love(Romeo)
print(Romeo+Juliet)
def look_for_love(Romeo):
Juliet = 4
```
##### 當程式離開 function,在裡面製造的 variable 就永遠消失了,會出現 Error: Name Juliet is not defined
- 羅密歐與茱麗葉在一起了!
```python=
def main():
Romeo = 4
Juliet = look_for_love(Romeo)
print(Romeo+Juliet)
def look_for_love(Romeo):
Juliet = 4
return Juliet
```
##### return 是救出變數、避免離開 function 後變數就會消失的唯一方法,此時 console 就可以印出 8 了!
### 5) 說明 <font color="#2CAC9E">**return**</font>
- 用來取得函式回傳值 (pass-by-value,否則離開 function,variable 都會消失)
- return 有終止 function 的功能
- 不可能會一次碰到兩個 return (類似while True的break)
### 6) Function 說明舉例 4:<font color="#2CAC9E">**stack frame**</font>
- error 版本,a 還是 0
```python=
def main():
print('-------------')
a = 0
plus_one(a)
print(a)
print('-------------')
def plus_one(a):
a += 1
```
- fixed,回傳後存入 a,a 為 1
```python=
def main():
print('-------------')
a = 0
a = plus_one(a)
print(a)
print('-------------')
def plus_one(a):
a += 1
return a
```
### 7) <font color="#2CAC9E">**return**</font> 與 <font color="#2CAC9E">**print**</font> 的不同
- print 會把當前 function 的值 print 出來,return 可以把值丟給其他的 function
- 若想在 main function print,就要 return 回 main function
- 想在當前 function 內 print,則不用 return
```python=
def main():
a=0
a=plus_one(a)
def plus_one(a):
a+=1
print(a)
```
- print 裡面也可以放 function,直接接 return 的回傳值,就不需要用變數箱子接
### 8) Key Concepts of Function
1. Variables don't share between function scopes
2. Communicate with arg/param(go in) and return(go out)
3. <font color="#2C7AAC">**User**</font>(arg)ument/<font color="AC2C7A">**Coder**</font>(param)eters
- <font color="#2C7AAC">**User 端**</font> (傳數值) 稱為arguments(arg)/<font color="AC2C7A">**Coder 端**</font> (接數值) 稱parameters(param)
4. Pass-by-value
- 不同 function 的變數 (variable) 不會共用,運算完就會被清掉
- 可以使用 return 留下結果,但不是把變數留下,而是把數值回傳
- 傳遞時跟箱子的名字無關,接的是數值
### 9) Function 說明舉例 5:<font color="#2CAC9E">my power function</font>
- <font color="#2C7AAC">**User 端**</font>
```python=
def main():
ans=my_power(3,4)
#3的4次方=81
```
- <font color="AC2C7A">**Coder 端**</font>
```python=
def my_power(a,b):
"""
:param a: int, a > 0
:param b: int, b >= 0
:return: int, a**b #python中a的b次方
"""
ans = 1
for i in range(b): #b控制跟a乘的次數
ans *= a
return ans
```
### 10) Function 說明舉例 6:<font color="#2CAC9E">predicate function</font>
##### return booleen type (True/False) 的 function
- <font color="#2C7AAC">**User 端**</font>
```python=
def main():
print("This program tells you if 'a' is an odd number.")
a = int(input('a: '))
print(is_odd(a))
#輸入7時得到True
```
- <font color="AC2C7A">**Coder 端**</font>
```python=
def is_odd(n):
"""
:param n: int, the num to be valued.
:return: bool, if n is an odd number or not.
"""
if n % 2 == 1:
return True
return False
```
- <font color="AC2C7A">**Coder 端**</font>精簡版 - 直接把問句放進 return
```python=
def is_odd(n):
"""
:param n: int, the num to be valued.
:return: bool, if n is an odd number or not.
"""
return n % 2 == 1
```
## 二、String
### 1) Data Types
#### 1. int
#### 2. float
#### 3. bool
#### 4. str (4 種 data type 中最複雜的)
### 2) str 延伸說明
- \ 是 back slash,告訴電腦要留意後面
- Escape sequence (所有由反斜線帶領出來的東西):
- ```\"```
```python=
print("\"")
#會印出以下
"
```
- ```\'```
```python=
print('\'')
#會印出以下
'
```
- ```\```
```python=
print('\\')
#會印出以下
\
```
- ```\n``` new line,代表會換行
```python=
print('Jerry\nLiao')
#會印出以下
Jerry
Liao
```
- ```\t``` tab,會隔一個 tab (4 個空白鍵)
```python=
print('Jerry\tLiao')
#會印出以下
Jerry Liao
```
- print 內建本來就已寫好會換行(有```\n```),所以不要換行的時候要加 ```end=""```
```python=
print('Jerry', end='!')
print('Liao', end='!')
#會印出以下
Jerry!Liao!
```
### 3) String 字串
###### ```S = 'stancode'```
#### 1. Index System
- 幫字串的每個字母編號,從 0 開始,稱為 Zero index
- 前面 stancode 每個字母是編號 0-7
#### 2. Get character
```python=
first = S[0] #'s'
last = S[7] #'e'
```
#### 3. Get length
```python=
l = len(s) #8
#len()是內建function
```
#### 4. Immutable of string
- 如果想把 stancode 的 c 改為大寫,用 ```S[4] = C``` 是沒辦法的!
- 就像一串串燒,已經串上去的就不能改了,需要拿掉不要的部分、從空的 string 重串!
### 4) 文字處理
#### 1. 要一個字母一個字母串
1. Start with an empty string (空竹籤)
2. Loop over the string
3. Concatenation
#### 2. 要怎麼把字串 stancode 的 c 換成大寫的
```python=
S = 'stancode'
ans = '' #製造空竹籤
for i in range(len(s)): #總共要串幾個字母
ch=s[i] #把原始的字串個別先存到ch
if ch ! = 'c': #判斷該字母要換掉還是留下
ans += ch #保留
else:
ans += 'C' #換
#得到 ans = stanCode
```