<style>
blockquote {text-align: left; font-size: 25px}
#u_try{color: #7FFF00; text-align: left; font-size: 30px}
#pl{color: #FFFFFF; text-align: left; font-size: 28px}
</style>
<!-- .slide: data-background="#000000" -->
# 程式語言的基本概念
###### tags: `Python` `50分鐘版` `中學資訊教育`
前往[演算法與資料結構投影片](https://hackmd.io/@Lance/rJAWmgbow)
前往[資訊科技與人類社會投影片](https://hackmd.io/@Lance/By1tJG_TD)
[成績資訊及學習歷程檔案範例](https://bit.ly/2RKrSJY)
----
<p id="dir">目錄:</p>
<ul>
<li><a href="#C1">CH1 輸出【2-1 ~ 2-7】</a></li>
<li><a href="#C2">CH2 變數【3-1 ~ 3-12】</a></li>
<li><a href="#C3">CH3 輸入【4-1 ~ 4-9】</a></li>
<li><a href="#C4">CH4 邏輯條件判斷【5-1 ~ 5-29】</a></li>
<li><a href="#C5">CH5 迴圈【6-1 ~ 6-32】</a></li>
<li><a href="#C6">CH6 一般陣列與字串陣列【7-1 ~ 7-41】</a></li>
<li><a href="#C7">CH7 函式【8-1 ~】</a></li>
<li><a href="#C8">CH8 遞迴【9-1 ~】</a></li>
<li><a href="#C7">CH9 樹【10-1 ~】</a></li>
<li><a href="#C8">CH10 圖【11-1 ~】</a></li>
</ul>
----
大家應該都了解電腦所懂的語言只有0和1
但…為何?
----

電壓影響了矽的導電與否,造就了0 和 1
0:不導電 1:導電
----
那為何我們不是用01語言與電腦溝通?
----
難以撰寫、維護、理解
----
高階程式語言
⇩

⇩
01程式語言(低階程式語言)
----
* 高階程式語言種類:
* <span><!-- .element: class="fragment highlight-red" data-fragment-index="1"-->Python</span>、Java、C、C++、JavaScript、… <br><br>
> <span><!-- .element: class="fragment" data-fragment-index="1" -->Python是這當中用途最廣泛又最易學的</span>
> <span><!-- .element: class="fragment" data-fragment-index="2" -->因此,本學期選定Python當作我們所學的第一個程式語言吧!</span>
----
開發環境:Pycharm
<p id=pl>新增python file</p>

----
<p id=pl>執行 和 結果</p>
 
----
每次上課都會有個小成品未來作為推甄學習歷程履歷使用
----
開始我們的第一個程式吧!
---
<p id='pl'><a href="#dir">回到目錄</a></p>
<h2 id="C1">CH1 輸出</h2>
----
### 印出字串
```python=
# 印出南港許光漢是我!
print("南港許光漢是我!")
# 印出天龍林依晨是我!
print("天龍林依晨是我!")
```
> ✍️ " " 雙引號內的內容我們稱作字串
> ✍️ `print()` 就是輸出的基本結構
----
<p id=u_try>【換你試試看】</p>
<p id=pl>請試著印出:</p>
> 菸一支一支一支的點 酒一杯一杯一杯的乾
> 請你要體諒我 我酒量不好賣給我衝康 (。´艸`。)
----
### 印出數字
```python=
# 6
print(3+3)
# 0
print(3-3)
# 9
print(3*3)
# 1.5
print(3/2)
# 0
print(3%3)
# 27
print(3**3)
# 1
print(3//3)
```
> ✍️ 數字不需要用 " " 刮起來
----
<p id=u_try>【換你試試看】</p>
<p id=pl>請試著印出:</p>
1. 利用所學的四則運算方法將下列式子無條件少去小數點
`(8 + 7) × 3 ÷ 4 - 3`
2. 試著比較下列三行程式碼
`print('3'+'3')`
`print('3', '3')`
`print('3+3')`
3. 試著比較下列兩行程式碼
`print('3'*3)`
`print(3*3)`
----
### <code>print()</code>的隱藏功能
<p id=pl>想想看,下列程式碼印出的結果應該是如何?<p>
```python=
print("*")
print("#")
```
<p id=pl>那該如何改成橫的印出呢?</p>
<p id=pl>其實python的<code>print</code>最後面內建「換行」的功能,我們可以在<code>print()</code>中加上<code>,end=''</code>讓原先最後面內建的換行能消失</p>
```python=
print("*", end='')
print("#", end='')
```
----
<p id=u_try>【想想看】</p>
<p id=pl>你覺得下方程式碼印出的結果應該為何?</p>
```python=
print("*", end='.7-11')
print("#")
print("*", end='.7-11')
print("#")
```
---
<p id='pl'><a href="#dir">回到目錄</a></p>
<h2 id="C2">CH2 變數</h2>
----
什麼是變數?
----
相信之前如果有學過一點點程式設計的大家都已經對「變數」這名稱不陌生了,我們可以簡單地把變數想像成為一個盒子,這個盒子可以一次裝一筆資料進去,但當我們再放新的一筆資料進盒子中時,前一筆資料就會被迫消失囉!
> ✍️ 變數其實就是個記憶體空間
----
為何需要變數?
----
電腦畢竟是人類所開發出的產品,因此思維模式肯定與人類相去不遠,人類不論從眼、耳、鼻、舌、手等感知器官所偵測到的訊息都會存放在腦中,因此,電腦也同樣需要一個空間儲存所得到的訊息,那就利用變數吧!
----
 ⇦ 
 ⇦ 
----
```python=
# box變數指定為100
box = 100
# box變數指定為300
box = 300
# 印出box變數內的值
print(box)
# 同時指定多個值到多個變數
num, ss, ff = 300, "I love the way u lie", 3.1416
# 同時印出多個變數中的值
print(num, ss, ff)
```
> ✍️ 等號在程式碼中是「指定」的意思
> ✍️ 變數放等號左邊,等號右邊的值用來指定到左邊變數中
----
<p id=u_try>【換你試試看】</p>
<p id=pl>創造三個變數(n1, n2, n3)分別指定為:16, "歲", "我的年紀是"</p>
<p id=pl>利用一個print( )程式碼想辦法印出下列結果:</p>
我的年紀是 16 歲
----
### 變數間的相互指定與操作
```python=
n1 = 1000
n2 = 5
# 沒有實質改到(整形)
n1 + n2
print(n1)
# 實質改變的方法一
n1 = n1 + n2
print(n1)
# 實質改變的方法二
n1 += n2
print(n1)
# 換個四則運算符號試試看
n1 /= n2
print(n1)
```
----
<p id=u_try>【換你試試看】</p>
<p id=pl>請讓 n1 的值變成 n2 的 n3 次方</p>
```python=
n1, n2, n3 = 10, 5, 3
# implement your code here
print(n1)
```
----
<p id=u_try>【挑戰看看】</p>
<p id=pl>想辦法讓 box1 box2 中的值交換</p>
```python=
# 指定box1的值為100
box1 = 100
# 指定box2的值為-2
box2 = -2
# implement your code here
# 印出box1和box2的值
print(box1, box2)# -2 100
```
----
### 變數的型態

---
<p id='pl'><a href="#dir">回到目錄</a></p>
<h2 id="C3">CH3 輸入</h2>
----
有了輸出當然也少不了輸入囉!!
<p id=pl>輸入的範例:</p>
```python=
i_n = input("請輸入你的大名:")
```
<p id=pl>印出輸入進來的值:</p>
```python=
print(i_n)
```
> ✍️ input進來的型態都是「字串」
<p id=pl>若要轉型態,寫法如下:</p>
```python=
i_n = input("請輸入一個數字:")
print(type(i_n)) # <class 'str'>
# 轉型態(str -> int)
i_n = int(i_n)
print(type(i_n)) # <class 'int'>
```
----
```python=
my_age = input("請輸入你的年紀:")
myfather_age = input("請輸入你爸爸的年紀:")
# 轉型態(str -> int)
my_age = int(my_age)
myfather_age = int(myfather_age)
print("你爸爸與你差", myfather_age-my_age, "歲")
```
<p id=pl>另一種較簡便的寫法:</p>
```python=
# 指定值給予變數前就先將型態由(str -> int)
my_age = int(input("請輸入你的年紀:"))
myfather_age = int(input("請輸入你爸爸的年紀:"))
print("你爸爸與你差", myfather_age-my_age, "歲")
```
----
<p id=u_try>【換你試試看看】</p>
<p id=pl>嘗試作出下列結果:</p>

----
<p id=u_try>【挑戰看看】</p>
<p id=pl>嘗試作出下列結果:</p>

----
<p id=pl>程式碼提示:</p>
```python=
print('-'*10 + '基本資料' + '-'*10)
# implement your code here
print('-'*27)
print("") # 想一下,這行作用為何?為什麼?
print('-'*10 + '自我介紹' + '-'*10)
# implement your code here
```
----
### 一次多值輸入
<p id=pl>有時候我們一次想輸入多筆資料,這時可以這樣寫</p>
```python=
n1, n2, n3 = input("請輸入身高、體重、年齡:").split()
```
<p id=pl>身高、體重、年齡分別會存入 n1, n2, n3 中(型態為字串)</p>
<p id=pl>將結果印出</p>
```python=
print(n3, n1, n2)
```
----
<p id=pl>不過,如果這時我們想將前頁n1, n2, n3的結果都改為整數型態,我們可以這樣寫</p>
```python=
n1, n2, n3 = map(int, input("請輸入身高、體重、年齡:").split())
```
----
<p id=u_try>【挑戰看看】</p>
<p id=pl>請寫一個程式讓使者能夠輸入姓名、身高(m)、體重(kg),並顯示出使用者的BMI值</p>
```python=
name, height, weight = input("請輸入姓名、身高、體重:").split()
______
______
print(______)
```
---
<p id='pl'><a href="#dir">回到目錄</a></p>
<h2 id="C4">CH4 邏輯條件判斷</h2>
----
### 布林值(bool)
----
|布林值|其他相同意思者|
|:---:|:---:|
|True|1、(others)|
|False|0、空(empty)|
----
```python=
statement = "今天林北北請大家吃王品"
my_age = 18
print(bool(statement)) #True
print(bool(my_age)) #True
print(bool(1)) #True
```
```python=
print(bool(False)) #False
print(bool(None)) #False
print(bool(0)) #False
```
----
<p id=u_try>【想想看看】</p>
```python=
bool(-289) # ???
bool(0.07) # ???
bool("") # ???
bool(" ") # ???
bool(()) # ???
bool([]) # ???
bool({}) # ???
```
----
### 比較運算符號
* 電腦科學中通常有6種比較關係:
* 比較運算符號的兩側,可以放常數、變數、運算式
* 比較的結果型態為boolean
<br>
|小於|大於|小於等於|大於等於|等於|不等於|
|:---:|:---:|:---:|:---:|:---:|:---:|
|<|>|<=|>=|==|!=|
----
比較運算的結果已經是True或False了,可以不必再用bool轉換它
```python=
num1 = 100
num2 = -10
print(bool(num1 <= num2)) # False
print(bool(num1 != num2 + 2)) # True
print(num1 <= num2) # False
print(num1 != num2 + 2) # True
```
----
### if 條件選擇
----
條件選擇,是藉由判斷條件,以選擇接下來要不要執行某一段程式
<p id=pl>以下是if的結構</p>
```python=
s = "cool"
if s == "cool": # 字串也適用
print("YES!") # 條件成立所以能執行這列程
```
----
> ✍️ Python中縮排是非常重要的,代表縮排的那幾列程式碼都屬於if判斷式下的程式碼,若判斷結果為False,則屬於其下方的式碼都不會被執行
> ✍️ 程式中的縮排通常按Tab鍵即可,不過要注意,在Python中,Tab按幾次會影響程式執行的正確與否,不得隨心所欲地按唷~
----
<p id=u_try>【想想看看】</p>
<p id=pl>以下程式碼會印出什麼結果</p>
```python=
if 1:
print("Yes!")
if 0:
print("NO!")
```
----
### else
----
* else 出現的時機就是不符合某個判斷條件時才要執行的程式,所以它一定要接在某個if後面
* 請記得if的區塊和else的區塊之間絕不能放任何程式(除了無意義的空行或空白以外)
----

```python=
if 50 != 50:
print("超過100分")
else:
print("錯誤") # if條件不成立會執行這列程式碼,若成立則不執行
print("光年之外")
```
----
<p id=u_try>【換你試試】</p>
> 一般來說,我們會以60分做為及格與否的標準,60分(含)以上為及格,不滿60分則是不及格,現在給你一個分數,請你判斷是否及格
>
> 輸入說明:
> 輸入一個整數 N (0<=n<=100) 代表要判斷的分數,不需要檢查它是否超出 0~100 的範圍
>
> 輸出說明:
> 若輸入的是及格的分數,請輸出 PASS,否則輸出 FAIL
----
<p id=u_try>【挑戰看看】</p>
> 如果一個整數是2的倍數,則它就是一個偶數,否則為奇數。給你一個整數,請你判斷它是奇數還是偶數
>
> 輸入說明:
> 輸入一個整數 N,即為要判斷的數
>
> 輸出說明:
> 若輸入的整數為奇數,則輸出 ODD,若為偶數則輸出 EVEN
----
### 邏輯運算符號
----
#### and(且)
||True|False|
|:---:|:---:|:---:|
|True|True|False|
|False|False|False|
```python=
if 1!=2 and 2>3:
print("判斷正確")
else:
print("判斷不正確")
```
----
#### or(或)
||True|False|
|:---:|:---:|:---:|
|True|True|True|
|False|True|False|
```python=
if 1>2 or 2==3:
print("判斷正確")
else:
print("判斷不正確")
```
> ✍️ 邏輯運算符號有優先順序性
----
<p id=u_try>【想想看看】</p>
<p id=pl>你覺得結果是如何?</p>
```python=
if 1 or 1 or 0:
print("判斷正確")
else:
print("判斷不正確")
```
----
### 多個相互獨立的條件判斷
<p id=pl>各條件之間互不影響</p>
```python=
name, height = input("請輸入您的 名字 及 身高 :").split()
height = int(height)
if height <= 155:
print(name, '好萌唷(๑˃̵ᴗ˂̵)ﻭ')
if 155 < height <= 180:
print(name, '凡人,您好')
if height > 180:
print(name, '走啦,打籃球啦!')
```
> ✍️ 同時輸入多筆資訊存入多個變數中:
> `name, height = input("提示字串").split()`
----
<p id=pl>請讓使用者輸入出生「月」及「日」並判斷他的星座為何</p>
```python=
m, d = map(int, input("請輸入您的出生「月」及「日」:").split())
if (m == 1 and d < 20) or (m == 12 and d > 21):
print("摩羯座")
if (m == 2 and d < 19) or (m == 1 and d > 19):
print("水瓶座")
if (m == 3 and d < 21) or (m == 2 and d > 18):
print("雙魚座")
if (m == 4 and d < 20) or (m == 3 and d > 20):
print("白羊座")
```
> ✍️ 有時會希望將輸入的所有變數一次全部都轉為某型態:
> `m, d = map(int, input("提示字串").split())`
> `m, d = map(float, input("提示字串").split())`
----
<p id=pl>然而,前述作法需要每個if都做判斷,相當沒有效率,因此我們可以改寫成下列方式:</p>
```python=
m, d = map(int, input("請輸入您的出生「月」及「日」:").split())
if (m == 1 and d < 20) or (m == 12 and d > 21):
print("摩羯座")
elif (m == 2 and d < 19) or (m == 1 and d > 19):
print("水瓶座")
elif (m == 3 and d < 21) or (m == 2 and d > 18):
print("雙魚座")
else:
print("其它星座")
```
> ✍️ `elif`只能接在`if`之後,只要其中任何一個條件成立,則不會再進行其後的條件判斷【較有效率】
----
<p id=u_try>【換你試試看看】</p>
<p id=pl>爸爸為了想讓我數學科目分數更高些,於是提議:<br>
如果我第一次段考超過70分就頒發1000元獎勵金<br>
如果我第二次段考超過80分就頒發2000元獎勵金<br>
如果我第三次段考超過90分就頒發3000元獎勵金<br>
分別輸入3次段考成績g1、g2、g3<br>
輸出最終我可以拿到多少獎勵金?</p>
```python=
g1, g2, g3 = map(int, input("請分別輸入三次段考成績:").split())
tmp = __________ # 新增一個變數專門用來儲存目前累積的獎金
if g1 >= 70:
__________
if g2 >= 80: # 可以改成elif嗎?
__________
if g3 >= 90: # 可以改成elif嗎?
__________
print(tmp) # 印出累積在變數中的獎金
```
----
<p id=u_try>【換你試試看看】</p>
<p id=pl>同一件商品在不同的商店可能有不同的售價,因此老一輩的人常常提醒我們:「貨比三家不吃虧」。現在給你同一件商品在三間不同商店的售價,請你找出最便宜的一個。<br>
<strong>輸入說明</strong>:<br>
輸入三個正整數,代表這件商品的三個售價。<br>
<strong>輸出說明</strong>:<br>
請輸出最便宜的售價,也就是三個售價中最小的那一個是多少。<br><br>
(提示:可利用一個變數儲存目前所找到的最小值)</p>
----
```python=
p1, p2, p3 = map(int, input("請輸入三個價格:").split())
tmp = __________ # 新增一個變數專門用來儲存目前找出最小的值
if __________ :
__________
if __________ :
__________
if __________ :
__________
print(tmp) # 印出儲存起來的值(三個數之中最小的那個)
```
----
### 多層次的條件判斷
<p id=pl>一個條件判斷完後還需要更深一層的判斷</p>
<p id=pl>2020肺炎全球大流行,政府決定對有出國史的人進行強制居家隔離,並對有出國史且有感冒者進行醫院隔離
請設計出一個自動問答程式讓使用者可以針對上述問題回答,最後決定出他是否不用隔離、居家隔離或醫院隔離</p>
```python=
trip = input("請問您14天內是否有出國過?(Y/N):")
if trip == "Y":
illness = input("請問目前身體是否有不適?(Y/N):")
if illness == "Y":
print("醫院隔離")
else:
print("居家隔離")
else:
print("不用隔離")
```
----
<p id=u_try>【換你試試看看】</p>
<p id=pl>由於地球公轉一周大約是365.242199日,所以如果以一年365日來記算,每四年就會多出0.968796天,於是有人提出每四年要多出一天,這就是閏年。但是因為每四年多出來的並非完整的一天,所以累積到100年的時候,就不須要再多這一天了。而同樣的道理,到了400年,又會多出一天來。<br>
目前閏年的規則如下(西元紀年):<br>
1. 如果這一年不是4的倍數,則它是平年。<br>
2. 如果這一年是4的倍數,但不是100的倍數,則它是閏年。<br>
3. 如果這一年是100的倍數,但不是400的倍數,則它是平年。<br>
4. 如果這一年是400的倍數,則它是閏年。<br>
現在給你一個年份,請你判斷它是不是閏年。<br>
<strong>輸入說明</strong>:<br>
輸入一個正整數 N,代表這是西元 N 年。<br>
<strong>輸出說明</strong>:<br>
若這一年是閏年,則輸出 YES,否則輸出 NO。
----
<p id=pl>程式碼提示:</p>
```python=
i = int(input("請輸入西元:"))
if __________ :
if __________ :
__________
else:
if __________ :
__________
else:
__________
else:
print("NO")
```
---
<p id='pl'><a href="#dir">回到目錄</a></p>
<h2 id="C5">CH5 迴圈</h2>
* 重複地做一樣的事情
* 用某個條件判斷決定是否結束不斷重複的輪迴
----
### while 迴圈基本結構
> ✍️ 迴圈最重要的一項要件:中止因素【條件判斷】
```python=
while True:
i = int(input("請輸入你的BMI值:"))
if i < 18 :
print("一個便當不夠那就吃兩個R")
elif i >= 18 and i <=24:
print("很邱逆")
else:
print("先去操場跑10圈再說")
```
```python=
while False:
print("芝麻開門")
```
----
<p id=u_try>【想想看】</p>
<p id=pl>下方的結果會為何?</p>
```python=
while bool("寶貝你好美"):
print("廢話")
```
```python=
while "媽媽" == "好吵":
print("完了")
```
```python=
while 20<30 and 30>40:
print("鬼話")
```
```python=
while 20<30 or 30>40:
print("神話")
```
----
#### while迴圈圈數控制
<p id=pl>常常,我們並不希望迴圈是無次數限制的,我們希望他做到某個條件後就能自動停止。這時,往往就需要額外使用變數來控制迴圈</p>
<p id=pl>方法一:(會改變到輸入原始值)</p>
```python=
i = int(input("請輸入一個整數"))
while i > 0: # i 只要 > 0 就可進入迴圈
print(i)
i -= 1 #每圈結束後讓i變數的值-1
```
<p id=pl>方法二:(不會改變到輸入原始值)</p>
```python=
i = int(input("請輸入一個整數"))
round = 1 # 新增一個變數用於紀錄執行了幾圈,從0開始
while round <= i: # round < i 用於判斷每一次能否進入迴圈
print(round)
round += 1 # 每圈結束後讓round變數的值+1
```
> ✍️ 注意!縮排一樣別忘記囉!
----
<p id=u_try>【想想看】</p>
<p id=pl>下方的結果會為何?</p>
```python=
while c < 10:
print(c)
c += 1
```
```python=
while c < 10:
c = 0
print(c)
c += 1
```
```python=
c = 0
while c < 10:
print(c)
```
```python=
c = 8
while c < 16:
print(c)
c += 2
```
----
<p id=u_try>【例題一】</p>
<pre>小邱很喜歡蚯蚓(~)
請寫一個程式能夠讀入一個整數
再印出該整數個"~"符號</pre>
<p id=pl>方法一:(會改變到輸入原始值)</p>
```python=
i = int(input("請輸入一個整數:"))
while ______ :
______
______
```
<p id=pl>方法二:(不會改變到輸入原始值)</p>
```python=
i = int(input("請輸入一個整數:"))
c = ______
while ______ :
______
______
```
----
<p id=u_try>【例題二】</p>
<p id=pl>小奇有一個很特殊的個性,就是非常討厭偶數,只要看到偶數,就會反覆把它除以二,直到這個數字變成奇數為止。現在給你一個正整數,請問你這個數字經過小奇的處理之後,會變成多少呢?</p>
```python=
i = int(input("請輸入一個偶數:"))
while ______:
______
print(i)
```
----
<p id=u_try>【換你試試看】</p>
<pre>細菌是非常細小的,除非到達一定的量,否則我們不容易發現它的存在。現在有一
種 X 菌,每隔一分鐘就會成長為原本的 3 倍,若它一開始只有 N 個,請問你
要經過幾分鐘才會繁殖到 M 個(含)以上呢?
<b>輸入說明</b>:
輸入二個正整數 N、M【N 是一開始 X 菌的數量,而 M 則是預計要達到的量】
<b>輸出說明</b>:
請輸出經過幾分鐘,X 菌才會達到 M 的量</pre>
```python=
n, m = map(int, input("請輸入一開始細菌的數量(N)及預計要達到的量(M):").split())
times = 0
while ______:
______
______
print(times)
```
----
#### while 搭配 if
<p id=pl>在條件判斷單元中,我們應該有練習如何判斷閏年與平年,但當時我們每一次要輸入都要重新執行程式一次,相當麻煩,現在我們可以利用while迴圈簡化這樣的繁瑣步驟</p>
```python=
while 1:
i = int(input("請輸入西元:"))
if i % 4 == 0 :
if i % 100 != 0 :
print("YES")
else:
if i % 400 != 0 :
print("NO")
else:
print("YES")
else:
print("NO")
```
----
<p id=u_try>【例題】</p>
<p id=pl>寫出一個猜數字遊戲範圍設定在0~1000之間的整數,事先寫一個答案,接下來每次輸入數字程式都會顯示出大於或小於直到顯示等於後結束</p>
```python=
ans = 520
while 1:
i = int(input("請猜一個1000內的正整數:"))
if i > ans:
print("答案小於您的猜測")
elif i < ans:
print("答案大於您的猜測")
else:
print("恭喜您猜對了")
```
----
<p id=u_try>【換你試試看】</p>
<p id=pl>寫一個程式,讓使用者能反覆輸入他的成績,並由成績計算出他所在的等第【A:100~90; B:89~80; C:79~70; D:69~60; E:59~0】,但當使用者輸入 -1 時,結束迴圈</p>
```python=
i = int(input("請輸入您的成績:"))
while ______ :
if i >= 90:
print('A')
elif i >= 80 and i < 90:
print('B')
elif i >= 70 and i < 80:
print('C')
elif i >= 60 and i < 70:
print('D')
else:
print('E')
______
print("迴圈結束")
```
----
#### while 搭配 break 或 continue
##### <font color="red">break</font>
希望迴圈在執行到某條件時就突然中止(不希望他執行到最後)
##### <font color="red">continue</font>
希望迴圈在執行到某條件時就直接進行下一輪迴圈(不希望他執行後面剩餘的程式碼)
----
#### break
<p id=pl>以前一題為例</p>
```python=
while 1 :
i = int(input("請輸入您的成績:"))
if i == -1:
break
elif i >= 90:
print('A')
elif i >= 80 and i < 90:
print('B')
elif i >= 70 and i < 80:
print('C')
elif i >= 60 and i < 70:
print('D')
else:
print('E')
print("迴圈結束")
```
----
#### continue
<p id=pl>只印出奇數</p>
```python=
i = 0
while i < 10 :
if i%2==0:
i += 1
continue
else:
print(i)
i += 1
```
<p id=pl>可以改寫成下列方式:(why?)</p>
```python=
i = 0
while i < 10 :
if i%2==0:
i += 1
continue
print(i)
i += 1
```
----
<p id=u_try>【想想看】</p>
<p id=pl>你覺得下方的結果會如何呢?</p>
```python=
i = 0
while i < 10 :
if i%2==0:
continue
i += 1
print(i)
i += 1
```
```python=
i = 0
while i < 10 :
print(i)
i += 1
if i%2==0:
continue
```
----
<p id=u_try>【換你試試看】</p>
<p id=pl>小怪獸很喜歡蒐集數字,從1開始,每次收集增加1的數字,但他討厭蒐集到5的倍數,因此,只要是<font color="red">5的倍數他就跳過不蒐集</font>,而如果蒐集到<font color="red">數字的總和超過200,小怪獸也會停止繼續蒐集</font>,並印出最終小怪獸蒐集到的數字總和</p>
```python=
num = 1
sum = 0
while 1:
if sum >= 200:
______
if num % 5 == 0:
______
______
else: # else其實可以省略
______
______
print(sum)
```
----
<p id=u_try>【玩玩看】</p>
<p id=pl>看看你能猜幾次才猜到電腦隨機產生1~1000的正整數</p>
```python=
import random
ans = random.randint(1, 1001)
count = 0
while 1:
i = int(input("請猜一個1000內的正整數:"))
count += 1
if i > ans:
print("答案小於您的猜測")
elif i < ans:
print("答案大於您的猜測")
else:
print("恭喜您猜對了")
print("您一共用了",count,"次 猜對了答案")
break
```
----
### for
<p id=pl>for迴圈則跟while迴圈非常相似,通常用哪種都可以,主要區別:<br>--> <font color="red">while迴圈通常會用在不知道要執行多少次的情況下</font><br>--> <font color="red">for迴圈通常用在已經知道要執行多少次的情況</font></p>
<p id=pl>例如:</p>
<p id=pl>1. 印出100個Hello【用for較佳】</p>
<p id=pl>2. 算出某個數字的某次方【用for較佳】</p>
<p id=pl>3. 算出某個數字的階乘【用for較佳】</p>
<p id=pl>4. 不斷輸入一個整數進行加總,若總和超過200則停止【用while較佳】</p>
<p id=pl>5. 讓使用者能夠不斷猜測一個未知的整數解答直到猜對為止【用while較佳】</p>
----
#### for迴圈的基本架構
```python=
# 從0-5,注意不包含6;i 每輪都+1
# 若range內只有一個變數代表終止值
for i in range(6):
print(i)
```
```python=
# 從2-5,注意不包含6;i 每輪都+1
# 若range內只有兩個變數代表「初始值」與「終止值」
for i in range(2, 6):
print(i)
```
```python=
# 從21-6,每輪都-3
for x in range(21, 3, -3):
print(x)
```
----
<p id=u_try>【例題一】</p>
<p id=pl>讓使用者能輸入一個整數n,印出1~n</p>
```python=
max = int(input("請輸入一個正整數"))
for i in range(______):
print(i)
```
<p id=pl>若用while改寫,可寫成</p>
```python=
max = int(input("請輸入一個正整數"))
______
while ______:
print(i)
______
```
----
<p id=u_try>【例題二】</p>
<pre>還記得那年參加跨年晚會的情景嗎?當台上的主持人大聲喊著:「倒數計時10秒
、9、8、7、6……」,隨著數字慢慢接近,大家的心情也隨之亢奮了起來
<strong>輸入說明</strong>:
輸入一個正整數 N,代表要開始倒數的秒數
<strong>輸出說明</strong>:
請輸出從 N 到 0 之間的所有整數</pre>
```python=
max = int(input("請輸入一個正整數"))
for i in range(______):
print(i)
```
----
<p id=u_try>【例題三】</p>
<pre>有句歌詞是這樣的「忠孝東路走九遍,穿過陌生人潮搜尋你的臉」(歌曲名:動力火車)
,台北的忠孝東路很長,真的走九遍要花很長的時間
<strong>輸入說明</strong>:
輸入一個正整數 N。
<strong>輸出說明</strong>:
忠孝東路走第1遍
忠孝東路走第2遍
...
忠孝東路走第N遍</pre>
```python=
num = int(input("請輸入一個正整數"))
for i in range(______):
print(______)
```
----
<p id=u_try>【挑戰題1】</p>
<pre>對於一個正整數 N 來說,如果它的因數只有 1 和 N 本身,沒有其他的因數,
則我們稱它為「質數」。現在給你一個正整數,請你判斷它是不是質數。
<strong>輸入說明</strong>:
輸入一個正整數 N。
<strong>輸出說明</strong>:
若 N 為質數,則輸出 是個質數,否則輸出 不是個質數。</pre>
> 提示:可能會需要額外的一個變數來記錄過程
> 測試:32582657 、 624108699802433
```python=
while True:
num = int(input("請輸入一個正整數:"))
______ # 用一個額外變數來紀錄是否有質數能夠整除num
for i in range(2, num):
if num % i == 0:
______
if ______:
print("不是個質數")
else:
print("是個質數")
```
----
<p id=u_try>【挑戰題2】</p>
<p id=pl>
進一步思考看看,能不能讓判斷 32582657 、 624108699802433 是否為質數的時間減少
</p>
```python=
import time
while True: # 用於能夠不斷輸入
num = int(input("請輸入一個正整數:"))
start = time.time() # 用於記錄現在的時間
______ # 用一個額外變數來紀錄是否有質數能夠整除num
for i in range(2, num):
if num % i == 0:
______
if ______:
print("不是個質數")
else:
print("是個質數")
print("總共用了",time.time() - start,"秒") # 計算出總共花費的時間
```
<p id=pl>
624108699802433 其實是兩個大質數的乘積,要分解出是哪兩個質數相乘其實不太容易,可用在現行的加密唷!
</p>
----
<p id=u_try>【挑戰題3】</p>
```python=
# 隨機產生一個介於0~1之間的數
from random import random
print(random()) # 0.8423085223647604
```
<p id=pl>
想想看,如何計算出圓周率是3.14159...呢?
<img src="https://i.imgur.com/f1KuvKh.png" width="300" hight="150">
</p>
```python=
from random import random
N = int(input("請輸入一個大一點的正整數用來計算圓周率π:"))
count = 0
for i in range(N):
x = ______
y = ______
if ______:
count += 1
print("PI =", ______)
```
<p id=pl>
再想想看,那圓面積為什麼是 半徑 x 半徑 x π 呢?
</p>
----
#### 巢狀迴圈
<p id=pl>巢狀迴圈顧名思義就是迴圈中還有迴圈的概念囉~~</p><img src="https://i.imgur.com/K6uIYui.png" width="230" height="160">
<p id=pl>相信大家對積木程式都已經不陌生了,先回想看看這題應該如何解?</p>
<img src="https://i.imgur.com/v9qk0Zp.png" width="280" height="280">
----
<p id=pl>先利用迴圈走完一個小三角形</p>
<img src="https://i.imgur.com/cUnh6EU.png" width="250" height="250">
<p id=pl>再利用一個迴圈走完12個相同的小三角形</p>
<img src="https://i.imgur.com/ytncKoy.png" width="250" height="250">
----
<p id=u_try>【例題一】</p>
<p id=pl>內外層迴圈互不相關</p>
<pre>
據說可愛的人都喜歡打飄號~~~輸入n和m,輸出n列的m個飄號
例如:n為3,m為5時,輸出:
~~~~~
~~~~~
~~~~~
</pre>
```python=
n, m = map(int, input("請輸入兩個正整數:").split())
for i in range(______):
for j in range(______):
print(______) # 要不能換行囉!
print("") # 換行
```
----
<p id=u_try>【例題二】</p>
<p id=pl>內外層迴圈相互關聯</p>
<pre>
輸入n,輸出n行🐣,第一行有1個,每往下一行,就多1個🐣
例如:n為4時,輸出如下
🐣
🐣🐣
🐣🐣🐣
🐣🐣🐣🐣
</pre>
```python=
n = int(input("請輸入一個正整數:"))
for i in range(______):
for j in range(______):
print(______)
print("")
```
----
<p id=u_try>【例題三】</p>
<p id=pl>內外層迴圈相互關聯</p>
<p id=pl>全半形切換:<code>shift</code>+<code>space</code></p>
<pre>
如果我希望的結果是這樣呢?
💧
💧💧💧
💧💧💧💧💧
💧💧💧💧💧💧💧
</pre>
```python=
n = int(input("請輸入一個正整數:"))
for i in range(______):
# 印出空白
for j in range(______):
print(______)
# 印出水滴
for j in range(______):
print(______)
# 換行
print("")
```
----
<p id=u_try>【例題三進階挑戰】</p>
<p id=pl>挑戰看看,你能不能僅用三行程式碼達到上頁相同結果?</p>
```python=
n = int(input("請輸入一個正整數:"))
for i in range(______):
______
```
----
<p id=u_try>【例題四】</p>
<p id=pl>嘗試利用巢狀迴圈製作一張九九乘法表吧!</p>
<img src="https://i.imgur.com/wRqs6FA.png" hight="400" width="800">
---
<p id='pl'><a href="#dir">回到目錄</a></p>
<h2 id="C6">CH6 一般陣列(List)與字串陣列(String)</h2>
----

----
<p id=pl>往往,我們需要儲存大量的資料,這時若我們只單純利用一堆變數儲存,那當然是相當沒效率又容易忘記變數名稱,這時我們就可以利用「陣列」</p>
* 陣列可視為一群變數的相連
* 陣列需要取一個名稱
* 陣列編號從0開始,且每一格都有其專屬編號
----
### 陣列的創造
> * <span style="color:red">注意!</span><span style="color:yellow">換列、空格</span>都算是一個字元唷!
> * 可利用<code>len()</code>計算出陣列的長度
一般陣列的創造
```python=
emptylist = [] # 空陣列
list5 = [1, 2, 3, 4, 5] # 創造一個陣列裡面分別存放1 2 3 4 5
countList = [-1] * 100 # 創造一個100格,裡面都是-1的陣列
countList2 = [0 for i in range(100)] # 創造一個100格,裡面都是0的陣列
fruitlist = ["apple", "banana", "cherry"]
print(len(fruitlist)) # ???
```
字串陣列的創造
```python=
emptystrlist = "" # 空陣列
strlist1 = "Wake Me up When September Ends"
strlist2 = "九月底 叫我起床"
print(len(strlist1)) # ???
print(len(strlist2)) # ???
```
----
### 得到陣列中的值
字串陣列
```python=
strlist1 = "Wake Me up When September Ends"
strlist2 = "九月底 叫我起床"
print(strlist1[4]) # ???
print(strlist2[4]) # ???
print(strlist1[5:15]) # ???
print(strlist1[0:15:2]) # ???
```
一般陣列
```python=
fruitlist = ["apple", "banana", "cherry"]
print(fruitlist[1], fruitlist[0]) # ???
print(fruitlist[1][3]) # ???
```
----
字串陣列與一般陣列間的轉換:
```python=
# list to string
fruitlist = ["apple", "banana", "cherry"]
a = ", ".join(fruitlist)
print(a) # "apple, banana, cherry"
# string to list 方法一
str1 = "refrigerator"
list1 = list(str1)
print(list1) # ['r', 'e', 'f', 'r', 'i', 'g', 'e', 'r', 'a', 't', 'o', 'r']
# string to list 方法二
str2 = "is it good to drink?"
list2 = str2.split()
print (list2) # ['is', 'it', 'good', 'to', 'drink?']
```
----
<p id=u_try>【換你試試看看】</p>
別逼一個最愛你的人 即興表演
什麼時候我們開始 沒有了底線
順著別人的謊言 被動就不顯得可憐
<br>
【請擷取上方歌詞的最後一列出來並印出】
----
<p id=pl>程式碼提示</p>
```python=
s = '''別逼一個最愛你的人 即興表演
什麼時候我們開始 沒有了底線
順著別人的謊言 被動就不顯得可憐'''
print(_____)
```
> ✍️ 多列字串我們會利用一對 ``` ''' ``` 或 ``` """ ``` 來表示
----
### 改變陣列中的值
<p id=pl>一般陣列</p>
```python=
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist) #['apple', 'blackcurrant', 'cherry']
```
<p id=pl>字串陣列</p>
> ✍️ 無法直接指定字串陣列中的某值,因此用.replace()代替
```python=
a = "電視裡我唱得用力,撕心裂肺誰又會在意"
print(a.replace(a[4], "罵")) # ???
```
----
<p id=u_try>【換你試試看看1】</p>
<p id=pl>電視裡我唱得用力,撕心裂肺誰又會在意</p>
<p id=pl>請將上列句子中「心」與「肺」利用<code>.replace()</code>分別改為「肝」與「腎」,並一次印出</p>
```python=
a = "電視裡我唱得用力,撕心裂肺誰又會在意"
______
______
print(a) # 電視裡我唱得用力,撕肝裂腎誰又會在意
```
----
<p id=u_try>【換你試試看看2】</p>
<p id=pl>請將陣列中編號0格子中的值與編號4格子中的值互換</p>
```python=
a = [5, 8, 18, -9, 7]
______
print(a)
```
----
### 找出陣列中是否有某個值
`<想找的值> in <某陣列>`
#### 一般陣列
```python=
athletelist = ["館長", "戴資穎", "林子偉"]
if "林子偉" in athletelist:
print("確實存在")
else:
print("很抱歉一切只是你的想像")
```
----
#### 字串陣列
<p id=pl>方法一</p>
```python=
txt = "臣亮言:先帝創業未半,而中道崩殂。今天下三分,益. 州疲敝,此誠危急存亡之秋也!"
if "孔明" not in txt:
print("確實不存在")
else:
print("很抱歉一切只是你的想像")
```
<p id=pl>方法二</p>
```python=
txt = "臣亮言:先帝創業未半,而中道崩殂。今天下三分,益. 州疲敝,此誠危急存亡之秋也!"
if txt.find('孔明') < 0: # 如果沒找到回傳值為-1
print("確實不存在")
else:
print("很抱歉一切只是你的想像")
```
----
<p id=u_try>【換你試試看看】</p>
<p id=pl>請寫一個程式找出下列文章中是否含有「神」字,如果有,請印出:太神啦;如果沒有,請印出:見鬼啦</p>
```python=
p = '''壬戌之秋哈,七月既哈望,蘇子與客泛舟遊於赤壁之下哈哈哈。清風徐來,水波不興。舉酒屬客,誦明月之詩,歌窈窕之章哈哈。少焉,月出於東山之上哈,徘徊於斗牛之間哈。白露橫江,水光接天。縱一葦之所如,凌萬頃之茫然。浩浩哈乎如馮虛御風,而不知其所止;飄飄乎如遺世獨立,羽化哈而登仙哈哈哈哈哈。
於是飲酒樂甚,扣舷而歌之。歌曰:桂棹兮哈蘭槳神,擊空明兮溯流光。渺哈渺兮予懷,望美人兮天一方。客有吹哈洞簫者,倚歌而和之。其聲嗚嗚然,如怨如慕,哈如泣如訴;哈餘音嫋嫋,不絕如哈縷。舞幽哈壑之潛蛟,哈泣孤舟之嫠婦。
蘇子愀然,正襟危坐,而問客曰:何爲其然也?客曰:月哈明星稀,烏哈鵲南飛。此非哈哈曹孟德之詩乎?西望夏口,東望武昌,山川相繆,鬱乎蒼蒼,此非孟德之困於周郎者乎?方其破荊州,下江陵,哈順流而東也,舳艫千里哈,旌旗哈蔽空,釃酒臨江,橫槊賦哈詩,固一世之雄也哈,而今哈安在哉哈?況吾與子漁樵於江渚哈之上,侶魚蝦哈而友麋鹿,駕一神之扁舟,舉匏樽以相屬,寄蜉蝣於天地,渺滄海之一粟。哀哈吾生之須臾,羨長江之無哈窮。挾飛仙以遨遊哈,抱明月而長終。知不可乎哈驟得,託遺響哈於悲風哈哈哈。'''
# implement your code here
```
----
### 陣列搭配迴圈
#### 一般陣列搭配迴圈
<p id=pl>印出一般陣列中奇數編號格子的值</p>
```python=
n_list = [25, 8, 10, 4, -3, -10]
for i in range(1, len(n_list), 2):
print(n_list[i])
```
#### 字串陣列搭配迴圈
<p id=pl>印出s字串陣列中編號為3的倍數的字</p>
```python=
s = '''別逼一個最愛你的人 即興表演
什麼時候我們開始 沒有了底線'''
for i in range(len(s)):
if i % 3 == 0:
print(s[i], end='')
```
```python
print(s[0::3]) # 當然,聰明一點可以寫成這樣
```
----
<p id=u_try>【換你試試看看】</p>
<p id=pl>請計算出下列赤壁賦文章中出現幾次「哈」</p>
```python=
p = '''壬戌之秋哈,七月既哈望,蘇子與客泛舟遊於赤壁之下哈哈哈。清風徐來,水波不興。舉酒屬客,誦明月之詩,歌窈窕之章哈哈。少焉,月出於東山之上哈,徘徊於斗牛之間哈。白露橫江,水光接天。縱一葦之所如,凌萬頃之茫然。浩浩哈乎如馮虛御風,而不知其所止;飄飄乎如遺世獨立,羽化哈而登仙哈哈哈哈哈。
於是飲酒樂甚,扣舷而歌之。歌曰:桂棹兮哈蘭槳神,擊空明兮溯流光。渺哈渺兮予懷,望美人兮天一方。客有吹哈洞簫者,倚歌而和之。其聲嗚嗚然,如怨如慕,哈如泣如訴;哈餘音嫋嫋,不絕如哈縷。舞幽哈壑之潛蛟,哈泣孤舟之嫠婦。
蘇子愀然,正襟危坐,而問客曰:何爲其然也?客曰:月哈明星稀,烏哈鵲南飛。此非哈哈曹孟德之詩乎?西望夏口,東望武昌,山川相繆,鬱乎蒼蒼,此非孟德之困於周郎者乎?方其破荊州,下江陵,哈順流而東也,舳艫千里哈,旌旗哈蔽空,釃酒臨江,橫槊賦哈詩,固一世之雄也哈,而今哈安在哉哈?況吾與子漁樵於江渚哈之上,侶魚蝦哈而友麋鹿,駕一神之扁舟,舉匏樽以相屬,寄蜉蝣於天地,渺滄海之一粟。哀哈吾生之須臾,羨長江之無哈窮。挾飛仙以遨遊哈,抱明月而長終。知不可乎哈驟得,託遺響哈於悲風哈哈哈。'''
count = 0
for i in range(______):
______
______
print(count)
```
<p id=pl>當然,你也可以簡單的使用<code>p.count("哈")</code>不過,還是請你先學會上面的方法吧!</p>
----
<p id=u_try>例題</p>
<p id=pl>請利用if-else判斷的方式,或搭配迴圈的方式找出 l 陣列中的最小值</p>
```python=
l = [25, 8, 10, 4, -3, -20]
min = ______
for i in range(______):
if ______:
______
print(min)
```
----
### 增加物件進陣列中
#### 一般陣列
<p id=u_try>方法一</p>
<p id=pl>可以利用<code>append(<object>)</code>方式加物件進陣列最末一個位置</p>
```python=
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist) #['apple', 'banana', 'cherry', 'orange']
```
<p id=u_try>方法二</p>
<p id=pl>也可以利用<code>insert(<position>, <object>)</code>方式加物件進陣列中的特定位置</p>
```python=
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist) #['apple', 'orange', 'banana', 'cherry']
```
----
#### 一次輸入多個值進陣列
```python=
lota_list = input('請輸入本期的大樂透號碼:').split() # 55 33 44 33 22 33
print(lota_list) # ['55', '33', '44', '33', '22', '33']
```
----
#### 字串陣列
```python=
a = "Is it good to drink?"
b = "水啦"
print(a+b)
```
----
<p id=u_try>【換你試試看1】<p>
<p id=pl>假設目前我已經有一個字串陣列:<code>s = "我達達的馬蹄是美麗的錯誤"</code>,請你將一個「聲」字加在「馬蹄」後方</p>
```python=
s = "我達達的馬蹄是美麗的錯誤"
______
print(s) # 我達達的馬蹄聲是美麗的錯誤
```
----
<p id=u_try>【換你試試看2】</p>
<p id=pl>利用迴圈設計一個讓使用者可以不斷輸入值並加進陣列中的程式,並且每次都將整個陣列印出</p>

```python=
l = []
while True:
num = input("請輸入一個正數:")
______
print(l)
```
----
### 移除陣列中的某值
#### 一般陣列
<p id=u_try>方法一:</p><p id=pl>使用<code>remove(<object>)</code>可移除陣列特定物件</p>
```python=
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist) # ['apple', 'cherry']
```
<p id=u_try>方法二:</p><p id=pl>使用<code>pop(<object>)</code>會移除陣列中最後一個物件</p>
```python=
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist) # ['apple', 'banana']
```
----
<p id=u_try>方法三:</p><p id=pl>使用<code><listname>.pop(<list_index>)</code>可移除陣列中指定索引值的物件</p>
```python=
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist) # ['apple', 'cherry']
```
<p id=u_try>方法四:</p><p id=pl>使用<code>del <list_name></code>可移除陣列中特定索引值的物件 或 移除整個陣列</p>
```python=
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist) #['banana', 'cherry']
```
```python=
thislist = ["apple", "banana", "cherry"]
del thislist
print(thislist) #NameError: name 'thislist' is not defined
```
----
#### 字串陣列
<p id=pl>同樣可利用<code>.replace()</code>來達到此目的</p>
```python=
txt = "臣亮言:先帝創業未半,而中道崩殂神。今天下三分,益. 州神疲敝,此誠危急存亡之秋也!"
txt = txt.replace('神', '') # 將「神」字給去除
print(txt)
```
----
<p id=u_try>【換你試試看】</p>
<p id=pl>利用.replace()將換行去除</p>
```python=
t = '''人之初
性本善
性相近
習相遠
狗不叫'''
# implement your code here
print(t)
```
----
### 複製整個一般陣列
<p id=pl>注意! python不得直接指定(reference)整個陣列到另一個變數,這會使得更動一個陣列另一個也會被動到</p>
```python=
thislist = ["apple", "banana", "cherry"]
li_tmp = thislist #這種指定方式非常危險
print(li_tmp) #['apple', 'banana', 'cherry']
thislist[0] = "WOOOW"
print(li_tmp) #['WOOOW', 'banana', 'cherry']
```
<p id=pl>要複製陣列請用<code><list>.copy()</code></p>
```python=
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist) #['apple', 'banana', 'cherry']
```
----
### 排序陣列中的值
<p id=pl>利用<code><list_name>.sort()</code>將陣列中的值自動由小到大排列</p>
```python=
num_list = [65, 20, 35, 100, 90, 36]
thislist = ["cherry", "banana", "apple", "orange", "kiwi", "melon", "mango"]
num_list.sort()
thislist.sort()
print(num_list)
print(thislist)
```
<p id=pl>若希望由大至小排列可以加上<code>reverse = True</code></p>
```python=
num_list = [65, 20, 35, 100, 90, 36]
thislist = ["cherry", "banana", "apple", "orange", "kiwi", "melon", "mango"]
num_list.sort(reverse = True)
thislist.sort(reverse = True)
print(num_list)
print(thislist)
```
----
<p id=u_try>【換你試試看】</p>
<p id=pl>利用迴圈設計一個讓使用者可以不斷輸入值並加進陣列中的程式,並且每次都將整個陣列由大至小印出</p>
<img src="https://i.imgur.com/66BUoDb.png" height = 150 width = 120>
```python=
p_list = []
while 1:
______
______
print(p_list)
```
----
<p id=u_try>【挑戰看看】</p>
<p id=pl>能否不利用現成的<code>.sort()</code>同樣達到上方例題由大至小的排序目標</p>
<img src="https://i.imgur.com/g7FhkpT.png" height=200 width=300><br>
```python=
p_list = []
while 1:
i = int(input('請輸入一個整數:'))
______ # 將i加進p_list陣列中
end = len(p_list)-1 # 記錄陣列中最後一格陣列編號
for n in range(end+1):
if p_list[n] >= p_list[end]:
______
else:
______
print(p_list)
```
----
### 陣列中最大值、最小值及總合
<pre>利用
<code>max(<list_name>)</code> <code>min(<list_name>)</code> <code>sum(<list_name>)</code>
找出陣列中最大值、最小值及總合</pre>
```python=
num_list = [65, 20, 35, 100, 90, 36]
print(max(num_list)) # 100
print(min(num_list)) # 20
print(sum(num_list)) # 346
```
----
<p id=u_try>【終極挑戰】</p>
<pre>
育成之聲電台為了方便讓聽眾點播歌曲,便將電台內所有取得授權的歌曲編號(1~100的正整數),聽眾在明信片上註明歌曲編號,即可完成點播。為了知道本年度最熱門的點播是哪一首,小亮亮把所有明信片翻了出來一張一張看,發現看到一半,就忘記每一首歌的點播次數了。現在想請你寫一個程式,幫小亮亮找出最熱門的歌曲是哪一曲。
輸入說明:
會有 N (1≤N≤20)個正整數,代表有N張明信片點播的歌曲編號
輸出說明:
請輸出點播次數最高的歌曲編號,以及它的點播次數(不用考慮最高點播次數的歌曲有兩首以上的情況),中間請空一格。
範例輸入:
55 33 44 33 22 33
範例輸出:
33 3
</pre>
----
<p id=u_try>程式碼提示</p>
```python=
music_list = input('請輸入點播音樂編號').split()
count = ______ # 開一個陣列用來記錄某歌曲編號被點播的次數
for ______ in range(______):
______
print(______ , ______)
```
<p id=pl>可以利用<code><list_name>.index(<value>)</code>得到某value所在陣列中的編號</p>
<p id=pl>例如:</p>
```python=
p = [20, 30, 10, -1]
print(p.index(-1)) # 3
```
----
### 多維陣列
#### 二維陣列


----
#### 三維陣列【參考即可】


----
#### 二維陣列的創造
<p id=pl>均為同一個值</p>
```python=
# 創造一個10x5的2維陣列內容均為0
twoDarray = [[0 for i in range(5)] for j in range(10)]
```
<p id=pl>每格不同值</p>
```python=
# 創造一個2x3的2維陣列
array_2D = [[1, 2, 3],
[4, 5, 6]]
# 印出陣列的row數
print(len(array_2D)) # ???
# 印出陣列的column數
print(len(array_2D[0])) # ???
```
> 二維陣列可用於矩陣(圖片)之類的
----
<p id=u_try>【想想看】</p>
```python=
# 創造一個2x3的2維陣列
twoDarray = [[1, 2, 3],
[4, 5, 6]]
print(twoDarray[1][0]) # ???
print(twoDarray[0][3]) # ???
print(twoDarray[1][1]) # ???
```
----
#### 二維陣列的存取
```python=
# 創造一個2x3的2維陣列
array_2D = [[1, 2, 3],
[4, 5, 6]]
for row in range(len(array_2D)):
for col in range(len(array_2D[0])):
print(f'第{row}列 第{col}行的值為:{array_2D[row][col]}')
```
> print(f'第{row}列 第{col}行的值為:{array_2D[row][col]}') 是將變數融合進字串的一種方式
----
<p id=u_try>【換你試試看】</p>
<p id=pl>請將陣列中所有值加總後印出</p>
```python=
array_2D = [[1, 2, 3],
[4, 5, 6]]
sum = 0
for row in range(______):
for col in range(______):
_______
print(sum)
```
----
#### 多維陣列的複製
<p id=pl>多維陣列若要複製,須使用copy.deepcopy(<list_name>),但需要import copy</p>
```python=
import copy
myList = [[0, 1, 2, 3],
[3, 2, 1, 0],
[3, 5, 6, 1],
[3, 8, 3, 4]]
cList = copy.deepcopy(myList)
myList[0][1] = 10
print(cList) # ???
print(myList) # ???
```
----
<p id=u_try>【終極挑戰】</p>
<p id=pl>美國總統大選,候選人老川因為太過忙碌剛好要從華盛頓州出發飛往佛羅里達州,沿途經過哪些州就去該州輔選,若希望總共停留的時間最短,則沿途應該停靠哪幾州?最終花費的時間為多少?【假設飛行的方向選擇只有下、右2種】</p>
 
----
<p id=pl>程式碼提示(程式碼可以滑動喔)</p>
```python=
# 到各州輔選所需要花費的時間
USAList = [[0, 4, 7, 1],
[6, 4, 2, 1],
[3, 1, 4, 2],
[5, 6, 1, 3]]
# 新開一個相同大小陣列紀錄走到每一格最少所需花費的時間
countList = [[0 for i in range(len(USAList[0]))] for j in range(len(USAList))]
for row in range(len(USAList)):
for col in range(len(USAList[0])):
# 跳過出發點
if ______
continue
# 先完成第一個row
elif row == 0:
______
# 再完成第一個column
elif col == 0:
______
# 其餘的從上方或左方選擇時間成本較小的州
else:
if countList[row-1][col] < countList[row][col-1]:
______
else:
______
# 將到達最終站-佛羅里達州時總共所花的時間印出
print(countList[len(USAList)-1][len(USAList[0])-1])
```
---
<p id='pl'><a href="#dir">回到目錄</a></p>
<h2 id="C7">CH7 函式</h2>
----
### 何謂函式?
想必大家應該不陌生,在數學科目中應該多少有接觸到吧!!

----


----
### 為什麼需要它?
<p id="pl">最主要其實是要將某個流程封裝、模組化,未來若需要進行同樣流程時,我們只需要呼叫這模組即可,程式碼能夠精簡化,也比較美觀
</p>
----
<p id="pl">人偶爾會幻想如果有個僕人能幫我做牛做馬的那該有多好啊!!其實函式就像是個專業的僕人,你可以請他幫你完成一些事,不過要記住,他是個專業的僕人,不是萬能的僕人,專業的僕人只會做專業的幾件事喔!</p>
 
----
### Python中的函式結構
<p id="pl">無回傳值、無參數輸入</p>
```python=
def wash_dish():
print('是!我立刻去洗盤子')
```
<p id="pl">無回傳值、有參數輸入</p>
```python=
def wash_dish(x):
print('是!我立刻去洗',x,'個盤子')
```
<p id="pl">有回傳值、無參數輸入</p>
```python=
def wash_dish():
s = "是!我立刻去洗盤子"
return s
```
<p id="pl">有回傳值、有參數輸入</p>
```python=
def wash_dish(x):
s = "是!我立刻去洗" + str(x) + "個盤子"
return s
```
----
### 函式呼叫
<p id="pl">1. 既然函式可以視作僕人,呼叫函式的就是主人囉!</p>
<p id="pl">2. 在主人還沒呼叫函式前函式是不會有動作的</p>
<p id="pl" style="color:red;">3. 函式必須在呼叫前先定義完成</p>
```python=
# 函式必須要先定義,但不會做出動作
def wash_dish():
s = "是!我立刻去洗盤子"
return s
# 主人開始呼叫函式,這時函式才開始動作
print(wash_dish()) # 是!我立刻去洗盤子
```
```python=
# 函式必須要先定義,但不會做出動作
def wash_dish(x):
s = "是!我立刻去洗" + str(x) + "個盤子"
return s
# 主人開始呼叫函式,這時函式才開始動作
print(wash_dish(5)) # 是!我立刻去洗5個盤子
```
----
請寫一個用來計算兩個數字總和的函式
<p id=pl>使用無回傳、無參數的方式撰寫(此方式不推薦)</p>
```python=
def add():
print(x + y)
x, y = map(int, input("請輸入兩個整數:").split())
add()
```
<p id=pl>使用無回傳、有參數的方式撰寫</p>
```python=
def add(a, b):
print(a + b)
x, y = map(int, input("請輸入兩個整數:").split())
add(x, y)
```
> 主人用x與y參數傳給僕人,僕人方相對應的參數改為a與b。當然,仍沿用x與y名稱也可以
----
<p id=pl>使用有回傳、無參數的方式撰寫(此方式不推薦)</p>
```python=
def add():
return x + y
x, y = map(int, input("請輸入兩個整數:").split())
print(add())
```
<p id=pl>使用有回傳、有參數的方式撰寫</p>
```python=
def add(a, b):
return a + b
x, y = map(int, input("請輸入兩個整數:").split())
print(add(x, y))
```
----
<p id=u_try>【例題】</p>
<p id="pl">請寫一個用來計算整個陣列數字總和的函式</p>
```python=
def sum(input_list):
count = 0
for i in range(len(input_list)):
count += input_list[i]
return count
num_list = [8, -7, 16, 5, -2]
print(sum(num_list))
```
----
<p id=u_try>換你試試看1</p>
<p id="pl">請寫一個計算階乘的函式</p>
```python=
def j_chen(num):
accumulate = 1
# implement your code here
return accumulate
x = int(input("請輸入一個正整數:"))
print(j_chen(x))
```
----
<p id=u_try>換你試試看2</p>
<p id="pl">請寫一個氣泡排序函式,用來將陣列中的值由大到小進行排序</p>
```python=
def bubble_sort(input_list):
# implement your code here
return input_list
num_list = [8, -7, 16, 5, -2, 50, 24]
print(bubble_sort(num_list))
```
----
<p id=u_try>【挑戰看看】</p>
<p id="pl">請寫一個計算最大公因數與最小公倍數的函式</p>
> 提示:僕人與僕人間可相互呼叫
```python=
def gcd(a, b):
# implement your code here
return ______
def lcm(a, b):
# implement your code here
return ______
while 1:
m, n = map(int, input("請輸入兩個整數:").split())
print("最大公因數為:", gcd(m, n))
print("最小公倍數為:", lcm(m, n))
```
---
<p id='pl'><a href="#dir">回到目錄</a></p>
<h2 id="C8">CH8 遞迴</h2>
----
 
----
以上狀態若想用數學式來表達該如何表達?
夢~n~ = 夢~n-1~ + 記憶
a~n~ = a~n-1~ + ?
----
Recursion(遞迴)
----
程式中的遞迴與數學中的遞迴其實是差不多的
----
觀察一下,遞迴有什麼必要的條件?
----
遞迴所需要的兩項要素:
1. 遞迴關係式(有回傳值)
👉 (記憶)
2. 有個最終停止的點
👉 (驚醒)
----
想想看,生活中有哪些遞迴呢?
----

----
<p id=u_try>【分析看看】</p>
高度為n的香檳塔共有多少個香檳杯

h~1~ = 1<!-- .element: class="fragment" data-fragment-index="1" -->
h~2~ = h~1~ + 2*2<!-- .element: class="fragment" data-fragment-index="2" -->
h~3~ = h~2~ + 3*3<!-- .element: class="fragment" data-fragment-index="3" -->
----
<p id=u_try>【歸納看看】</p>
1. 遞迴關係式?
h~n~ = h~n-1~ + n*n<!-- .element: class="fragment" data-fragment-index="1" -->
2. 有個最終停止的點?
h~1~ = 1<!-- .element: class="fragment" data-fragment-index="2" -->
----
<p id=u_try>【實作看看】</p>
```python=
def sum_champagne_glass(h):
if h == 1:
return 1
else:
return h*h + sum_champagne_glass(h-1)
```
可簡化為:
```python=
def sum_champagne_glass(h):
if h == 1:
return 1
return h*h + sum_champagne_glass(h-1)
```
----
若用迴圈實作:
```python=
def sum_champagne_glass(h):
sum = 0
for i in range(1, h+1):
sum += i*i
return sum
while 1:
i = int(input("請輸入層數:"))
print('總共有:',sum_champagne_glass(i),'個酒杯')
```
----
遞迴並不是在任何情況下都比迴圈來的好用
遞迴就只是自己呼叫自己的函式
----
<p id=u_try>【例題1】</p>
請用遞迴方式計算出階乘
<p id=u_try>【分析看看】</p>
j~0~ = 1<!-- .element: class="fragment" data-fragment-index="1" -->
j~1~ = j~0~ * 1<!-- .element: class="fragment" data-fragment-index="2" -->
j~2~ = j~1~ * 2<!-- .element: class="fragment" data-fragment-index="3" -->
j~3~ = j~2~ * 3<!-- .element: class="fragment" data-fragment-index="4" -->
----
<p id=u_try>【歸納看看】</p>
1. 遞迴關係式?
j~n~ = j~n-1~ * n<!-- .element: class="fragment" data-fragment-index="1" -->
2. 有個最終停止的點?
j~0~ = 1<!-- .element: class="fragment" data-fragment-index="2" -->
----
```python=
def factorial(n):
if ______:
return ______
return ______
while 1:
i = int(input('請輸入您想計算的階乘:'))
print(factorial(i))
```
換用迴圈實作看看
```python=
def factorial(n):
accumulate = 1
for i in range(______):
______
return accumulate
while 1:
i = int(input('請輸入您想計算的階乘:'))
print(factorial(i))
```
----
<p id=u_try>【例題2】</p>
請用遞迴方式計算費氏數列
<p id=u_try>【分析看看】</p>
f~0~ = 0<!-- .element: class="fragment" data-fragment-index="1" -->
f~1~ = 1<!-- .element: class="fragment" data-fragment-index="2" -->
<p>f<sub>2</sub> = f<sub>1</sub> + f<sub>0</sub></p> <!-- .element: class="fragment" data-fragment-index="3" -->
<p>f<sub>3</sub> = f<sub>2</sub> + f<sub>1</sub></p> <!-- .element: class="fragment" data-fragment-index="4" -->
----
<p id=u_try>【歸納看看】</p>
1. 遞迴關係式?
<p>f<sub>n</sub> = f<sub>n-1</sub> + f<sub>n-2</sub></p><!-- .element: class="fragment" data-fragment-index="1" -->
2. 有個最終停止的點?
f~0~ = 0 <!-- .element: class="fragment" data-fragment-index="2" -->
f~1~ = 1 <!-- .element: class="fragment" data-fragment-index="3" -->
----
```python=
def fib(n):
if ______:
______
elif ______:
______
return ______
while 1:
i = int(input('請輸入您想計算的費氏數列值:'))
print(fib(i))
```
----
可用迴圈改寫為:
```python=
def fib(n):
fib_h = 0; fib_t = 1
if ______:
return fib_h
elif ______:
return fib_t
else:
for i in range(______):
______
______
______
return fib_sum
while 1:
i = int(input('請輸入您想計算的費氏數列值:'))
print(fib(i))
```
----
<p id=u_try>【例題3】</p>
請用遞迴方式計算河內塔
<p id=u_try>【分析看看】</p>
one sheet 
two sheets 
----
three sheets 
ten sheets 
----
思考看看,n個盤子需移動幾次呢?
----
n sheets 
----
<p id=u_try>【歸納看看】</p>
1. 遞迴關係式?
<p>H<sub>n</sub> = H<sub>n-1</sub> * 2 + 1</p><!-- .element: class="fragment" data-fragment-index="1" -->
2. 有個最終停止的點?
H~1~ = 1 <!-- .element: class="fragment" data-fragment-index="2" -->
----
```python=
def Hanoi(n):
if ______:
______
return ______
while 1:
i = int(input('請輸入盤子數:'))
print("共需移動", Hanoi(i), "步")
```
----
若希望印出所有移動過程(從哪柱移動至哪柱)該如何實踐?
```python=
def Hanoi(n, a, b, c):
if n == 1:
print(f'將盤子由 {a}柱 移動至 {c}柱')
return 1
return ______
while 1:
i = int(input('請輸入盤子數:'))
print("共需移動", Hanoi(i, 'A', 'B', 'C'), "步")
```
----
用迴圈實作看看
----
```python=
def merge(left, right):
if not len(left) or not len(right):
return left or right
result = []
i, j = 0, 0
while (len(result) < len(left) + len(right)):
if left[i] < right[j]:
result.append(left[i])
i+= 1
else:
result.append(right[j])
j+= 1
if i == len(left) or j == len(right):
result.extend(left[i:] or right[j:])
break
return result
def mergesort(list):
if len(list) < 2:
return list
middle = ______
left = ______
right = ______
return merge(left, right)
print(mergesort([3, 4, 5, 1, 2, 8, 3, 7, 6]))
```
----
{"metaMigratedAt":"2023-06-15T12:27:43.454Z","metaMigratedFrom":"YAML","title":"程式語言的基本概念","breaks":true,"slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"82586838-6b25-424c-87e2-bd47d9cdac2b\",\"add\":101884,\"del\":58881}]"}