## Python語法 - Part 2
### Foxyy
---
## 目錄
- [迴圈](#/2/0)
- [函式](#/3/0)
- [常用函式&語法](#/4/0)
---
## 迴圈
用來重複執行一段代碼的程式結構
----
## for 迴圈
```python
for item in obj:
# ...
```
----
### 範例
```python=1
fruits = ['apple', 'orange', 'grape']
for fruit in fruits:
print(fruit)
# apple
# orange
# grape
```
```python=1
numberList = [101, 1001, 10001]
pro = 1
for i in range(3):
pro *= numberList[i]
print(f'The product is: {pro}')
# The product is: 1011111101
```
----
## while 迴圈
```python
while condition:
# ...
```
----
### 範例
```python=1
hunger = 2
while hunger < 20:
hunger += 5
print('Eat bread')
# Eat Bread
# Eat Bread
# Eat Bread
# Eat Bread
```
```python=1
num = 10
while num < 20:
num += 4
print(num, end=' ')
while num > 16:
num -= 1
print(num, end=' ')
# 14 18 22 21 20 19 18 17 16
```
----
## `break`, `continue`
`break`: 中斷迴圈
`continue`: 進入下一次迴圈
在 `for` 和 `while` 中皆可使用
----
### 範例
```python=1
for i in range(10):
if i % 3 == 0:
continue
print(i, end=' ')
# 1 2 4 5 7 8
```
```python=1
a = 35
for i in range(2, a+1):
if a % i == 0:
print(f'{i}是{a}最小的質因數')
break
# 5是35最小的質因數
```
----
## 範例
無窮迴圈 (考拉茲猜想)
```python=1
record = []
x = 30
while True:
if x in record:
break
record.append(x)
if x%2 == 0:
x //= 2
else:
x = x*3+1
record.append(x)
print(record)
```
----
### 練習題
https://oj.crc.cnmc.tw/problem/ITC_P04
提示:

---
## 函式 (function)
可以讓程式碼更乾淨,也更好除錯的工具
```python
def f(arg1, arg2, ...):
# ...
```
----
```python=1
def f(x):
return x**3 + 2 * x**2 + 4 * x + 8
# f(x) = x^3 + 2x^2 + 4x + 8
```
```python=1
def add(a, b):
return a+b
```
```python=1
def mul2(lst):
return_list = []
for i in range(len(lst)):
return_list.append(lst[i]*2)
return return_list
```
----
#### 不好的範例
```python=1
print('There are 10 apples and now there is none.')
print('There are 5 oranges and now there is none.')
print('There are 30 pineapples and now there is none.')
print('There are 20 bananas and now there is none.')
print('There are 15 grapes and now there is none.')
```
----
#### 好的範例
```python=1
def output(arg):
print(f'There are {arg} and now there is none.')
arg_list = ['10 apples', '5 oranges', '30 pineapples', '20 bananas', '15 grapes']
for arg in arg_list:
output(arg)
```
----
### 練習題
https://oj.crc.cnmc.tw/problem/ITC_P05
提示:

---
## 常用函式 & 語法

----
### ASCII Table

----
### 運算子優先度

---
# 謝謝大家 :fox_face:
{"metaMigratedAt":"2023-06-16T04:36:34.888Z","metaMigratedFrom":"YAML","title":"Python語法 - Part 2","breaks":true,"contributors":"[{\"id\":\"4f731eff-9d88-41f4-af56-2e3e02f20cfc\",\"add\":12,\"del\":0},{\"id\":\"3e931549-115e-4be2-b9ee-0f49862e387d\",\"add\":5508,\"del\":2755}]"}