---
tags: python
---
# 03_迴圈
## for 迴圈
* 宣告迴圈種類(for)
* 宣告一個疊代子 iterator (可自由命名)
* 宣告一個迴圈要跑的sequence (list, dict...)
```python
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
for wk in weekdays:
# 一次印出一天
print(wk)
# Monday
# Tuesday
# Wednesday
# Thursday
# Friday
# 從1數到5
# range()函數第一個參數為開始索引值(不填寫則預設為0)
# range()函數第二個參數為結束索引值,但不包含結束索引值本身
for n in range(1, 6): # 需要數到5,因此第二參數填入5 + 1
print(n)
# 1
# 2
# 3
# 4
# 5
```
### 印出九九乘法表
```python
for i in range(1, 10):
for j in range(1, 10):
print(f'{i} x {j} = {i * j}')
'''
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
...中間略...
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
'''
```
### 用for迴圈做出sum()函數背後的邏輯
```python
nums = [2, 4, 5, 8, 10]
print(sum(nums)) # 29
# 預設一個變數為0
summation = 0
# 將串列資料依次取出加進去
for num in nums:
summation += num
# 迴圈結束後印出結果
print(summation) # 29
```
### 用for迴圈遍歷一個字典
```python
dog = {'age': 3, 'breed': 'beagle', 'size': 'medium'}
# 如果sequence是一個字典,迴圈只會印出Key
for info in dog:
print(info)
# age
# breed
# beagle
# 取得字典內的值,方法一
for info in dog:
print(dog[info])
# 取得字典內的值,方法二
for value in dog.values():
print(value)
# 3
# beagle
# medium
# 同時取得字典內的Key: Value
for info, value in dog.items():
print(info, value)
# age 3
# breed beagle
# size medium
```
### 收支計算
```python
'''
透過迴圈計算餘額(balance)欄位
計算每月紀錄所有income, expense, balance的加總
'''
records = [ {"income": 40000, "expense": 23000}, {"income": 60000, "expense": 54000}, {"income": 22000, "expense": 35000}, {"income": 32000, "expense": 40000}, {"income": 70000, "expense": 20000} ]
# 預設income及expense加總為0
total_income = 0
total_expense = 0
for record in records:
record['balance'] = record['income'] - record['expense']
total_income += record['income']
total_expense += record['expense']
print(records) # 印出加上balance欄位後的收支紀錄
print(total_income) # 224000
print(total_expense) # 172000
```
### 最常與for迴圈併用的函數enumerate()
```python
bus_list = [
{'name': '643', 'arrive_time': 1},
{'name': '648', 'arrive_time': 3},
{'name': '綠1', 'arrive_time': 15},
{'name':'644','arrive_time': 30}
]
# i為索引值,bus為迭代子
for i, bus in bus_list:
name = bus['name']
time = bus['arrive_time']
report = f'第{i}班即將進站公車為{name},將於{time}分鐘後抵達'
print(report)
# 第1班即將進站公車為643,將於1分鐘後抵達
# 第2班即將進站公車為648,將於3分鐘後抵達
# 第3班即將進站公車為綠1,將於15分鐘後抵達
# 第4班即將進站公車為644,將於30分鐘後抵達
```
### 用zip()函數一次跑多個sequence
```python
name_list = ['seq1', 'seq2', 'seq3']
seq_list = ['ATTA', 'CGTA', 'ATCG']
for name, seq in zip(name_list, seq_list):
seq_set = {
'name': name,
'seq': seq
}
seq_collection.append(seq_set)
print(seq_collection)
# [{'name': 'seq1', 'seq': 'ATTA'}, {'name': 'seq2', 'seq': 'CGTA'}, {'name': 'seq3', 'seq': 'ATCG'}]
```
### 串列生成式
使用生成式generator快速產生需求串列
```python
# 生成1到100的偶數串列
# 當n可以被2整除餘數為0時,即為偶數
even_nums = [n for n in range(1, 101) if n % 2 == 0]
print(even_nums)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
```
## while迴圈
* 不確定會執行幾次的迴圈就必須使用while迴圈
* 所有for迴圈都可以用while迴圈改寫,反之則不一定
### while迴圈的結構
```python
while 某個判斷條件為`True`時:
# 執行甚麼事
```
### 從0開始累加,+1+2+3..到多少時會超過1000
```python
# 預設總和為0
summation = 0
# 開始要加的數字為1
n = 1
# 紀錄每個被加過的數字
records = []
# 當總和還是<=1000,就讓迴圈繼續跑
while summation <= 1000:
summation += n
records.append(n)
n += 1
print(records[-1]) # 最後一個被加的數字為45
print(summation) # 1035
```
### Fibonacci數列
```python
'''
fn = fn-1 + fn-2
試著取得第20個fibonacci數字是多少
'''
f1 = 1
f2 = 1
fibonacci = [f1, f2]
# 當資料數量為20時,即<20為`False`,迴圈結束
while len(fibonacci) < 20:
fib = fibonacci[-1] + fibonacci[-2]
fibonacci.append(fib)
print(fibonacci[-1]) # 6765
```
> Written with [StackEdit](https://stackedit.io/).
<!--stackedit_data:
eyJoaXN0b3J5IjpbNjM4MDQ0MTYzXX0=
-->