# 資研 12/8 社課講義
[**提問表單**](https://forms.gle/z4dPC1JPV6uA2q9w7)
---
## While迴圈 While Loops
1. 基本架構
```python=
while '條件式':
'要執行的程式碼'
```
2. 和for迴圈作用相似,主要使用時機為<font color="#CE0000">**不知道確切要執行幾次時**</font>
3. <font color="#CE0000">**也可**</font>使用`continue`、`break`、`pass`控制執行條件
4. 若不想在條件式內撰寫太複雜的條件,可使用
```python=
while True:
'要執行的程式碼+跳出迴圈之條件'
```
**要記得檢查跳出迴圈的條件,否則會造成<font color="#CE0000">無窮迴圈**</font>
```python=
i = 0
while i<2:
i += 1
print(i)
```
:::warning
**常見使用情景-多次輸入**
- 範例1.請你寫一個程式,當使用者輸入一個數字就回傳該數的平方,若輸入0則該程式停止
```python=
while True:
a = int(input())
if a == 0: break
else:
print(a**2)
```
:::
- 範例2.請利用while loops計算1+2+3+4+5+...+n<2023,n最大為多少
```python=
i = 1
s = 0
while s+i < 2023:
s += i
i += 1
print(s, i)
```
## 單行多次輸入
- 用於:單行內多次輸入
- `.split()`:將整個字串讀入,依空白去分割數值
```python=
a = input('提示訊息:')
print(a)
# 輸出:提示訊息:11 12 13 14 15
# 11 12 13 14 15
a, b, c, d, e = input('提示訊息:').split()
print(a, b, c, d, e)
print(type(a))
# 輸出:提示訊息:11 12 13 14 15
# 11 12 13 14 15
# <class 'str'>
```
## 列表 List
:::warning
**資料型態**
| Text | Numeric | boolean |
|:----:|:-------:|:------:|
| `string` | `int`、`float` | `bool` |
- 容器
| Sequence | Mapping | Set |
|:--------:|:-------:|:----:|
| `list`、`tuple` | `dict` | `set` |
:::
### 宣告列表
- 列表表示方法:`[]`
- 宣告:
```python=
L = ['apple', 'bananas']
L = list(('apple', 'bananas'))
```
- 若 `[]` 內不放任何元素,即創建**空列表**
- 列表內可放置**多個元素**
- 利用 `list()` 將其他資料型態轉為列表
- 列表內之元素**不限於單一資料型態**
>數字、字串、布林值皆可置於列表內
```python=
# 多個元素
L1 = ['apple', 'bananas']
print(L1, type(L1))
# 輸出:['apple', 'bananas'] <class 'list'>
# 將其他東西轉成列表
T = ('apple', 'bananas')
print(type(T))
L1_ = list(T)
print(L1_, type(L1_))
# 輸出:<class 'tuple'>
# ['apple', 'bananas'] <class 'list'>
# 不限單一資料型態
L2 = ['a', 1, True]
print(L2)
# 輸出:['a', 1, True]
# 空列表
L3 = []
print(L3)
# 輸出:[]
```
### 有序資料型態(容器)
- index:類似於座號,為該容器的元素進行編號

[圖片出處](https://www.scaler.com/topics/index-in-python/)
- 列表為有序容器,可透過index去取得對應編號的元素
- 語法:`列表名稱[index]`
```python=
L = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print(L)
# 輸出:['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print(L[0])
# 輸出:Monday
print(L[4])
# 輸出:Friday
```
---
## **練習題**
**Zerojudge**
[**連結**](https://zerojudge.tw/)
---
## 補充資料
**推薦網站:**[**W3Schools**](https://www.w3schools.com/)