# 第一階段複習
siriuskoan
---
## Outline
- 變數與型別
- 邏輯判斷 `if`
- 迴圈 `for`、`while`
- string
- `list`
- `dict`
- 函式
- module
---
## 先複習一下 IO
```python=
name = input("輸入名字: ")
print("Your name is", name, sep=" ", end="!")
```
---
## 變數與型別
變數是存放值的容器
型別代表這個變數(值)的類型
----
## 型別
- `int`
- `str`
- `float`
- `list`
- ...
----
## 運算子
- `+`、`-`、`*`、`/`、`//`
- `&`、`|`、`^`、`~`
- `and`、`or`、`not`
----
## 範例
```python=
# int
a = 1
a2 = a + 5
a3 = a2 * 2
# float
b = 1.0
# str
c = str(a)
c *= 10
# list
d = [1, "1"]
```
----
## Quiz
*階段考不會出現*
What's the output?
```python=
a = 12
a = str(a)
a1 = int(a) + 1
a2 = a * 2
a3 = int(a) + 3 // 2
print(a1, a2, a3)
print(type(a1), type(a2), type(a3))
```
---
## 邏輯判斷 `if`
判斷一個條件是否為真,並根據結果做不同的事情
----
## 範例
```python=
score = int(input("輸入分數: "))
if score >= 90:
print("A+")
elif score >= 85:
print("A")
elif score >= 80:
print("A-")
else:
print("no A")
```
----
## `=` vs. `==`
- `=`
- 賦值
- 把一個變數的值設定成某個值
- `==`
- 判斷
- 判斷兩個值是不是相同
----
## Quiz
What's the output?
```python=
# credit to 鄧人豪
x = 2
y = 3
bool1 = x == y
bool2 = x = y
print(bool1, bool2)
print(x, y)
```
---
## 迴圈 `for`、`while`
在某個條件成立時重複執行特定片段的程式
- `while`
- 通常在有一個確定條件來決定是否要迴圈時使用
- 如: `name == ""`
- `for`
- 通常在確定(常數或是變數都可以)要跑幾次的時候使用
- 如: 倒數計時器
----
## 範例
```python=
# while
name = input("請輸入名字: ")
while name == "":
print("名字不得為空")
name = input("請輸入名字: ")
print("Welcome, " + name)
```
----
## 範例
```python=
# for
import time
count = int(input("從多少開始倒數: "))
for i in range(count, -1, -1):
print("倒數到: " + str(count))
time.sleep(1)
print("倒數結束")
```
----
## 迴圈控制
- `break`
- 直接中斷現在的**整個**迴圈
- `continue`
- 跳過現在正在進行的**這一次**迴圈
----
## 範例
```python=
name = input("請輸入名字: ")
while True:
print("名字不得為空")
name = input("請輸入名字: ")
if name != "":
break
print("Welcome, " + name)
```
----
## 範例
- `range` 左閉右開
```python=
MAX = 0
for n in range(10):
n = int(input("輸入 0 ~ 100 的數字: "))
if n > 100 or n < 0:
print("範圍錯誤")
continue
MAX = max(MAX, n)
print("最大值是 " + str(MAX))
```
----
## 巢狀迴圈
```python=
for i in range(1, 10):
for j in range(1, 10):
print(f"{i}*{j}={i*j}", end=" ")
print()
```
----
## Quiz
輸出 0 到 1 的每個小數,取到小數點後第二位
即,$0.00,0.01,0.02,...,0.99,1.00$
----
### Ans
```python=
for i in range(0, 101):
print("%.2f" % round(i / 100, 2))
```
---
## String
一大堆字連在一起
----
## 範例
```python=
s1 = "abc"
s2 = 'abc'
s3 = """abc
123"""
```
----
## 字串格式化
```python=
name = "siriuskoan"
print("My name is {}".format(name))
print(f"My name is {name}")
```
----
## 字串操作
```python=
string = "I love cat"
# 長度
print(len(string))
# 索引
print(string[2])
# 分割
print(string[2:6])
```
----
## 字串處理函式
```python=
string = "I love dog"
# replace
print(string.replace("dog", "cat"))
# find
dog_index = string.find("dog")
print(f"The word dog is at {dog_index} to {dog_index + 2}")
# split
data = "Shohei Ohtani,57,17,.298".split(",")
print(f"Player: {data[0]} AB: {data[1]} \
H: {data[2]}, AVG: {data[3]}")
```
----
## 字串處理函式 (cont.)
```python=
# join
like = ["Reading", "Coding", "Gaming"]
print("I like " + ", ".join(like))
# strip
name = input("名字: ")
# name is " siriuskoan "
print(name.strip())
```
---
## `list`
可以裝好幾項資料的資料結構
----
## 範例
```python=
li = [1, 2, 3]
for ele in li:
print(ele)
# or
for i in range(len(li)):
print(li[i])
```
----
## 分割
```python=
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(li[0:5])
print(li[:-1])
print(li[::-1])
```
----
## 串列操作
```python=
li = [1, 2, 3, 4, 5]
li.append(6)
li.extend([7, 8])
li.insert(0, 0)
print(li.index(3))
print(li.count(1))
li.pop()
li.remove(0)
li.clear()
```
----
## 串列操作 (cont.)
```python=
li = [2, 3, 9, 7, 6, 0]
print(list(reversed(li)))
li.reverse()
print(sorted(li))
li.sort()
```
----
## `list` 的指派
```python=
L1 = [1, 2, 3, 4, 5]
L2 = L1
L2[0] = -1
print(L1, L2) # 相同
```
vs.
```python=
L1 = [1, 2, 3, 4, 5]
L2 = L1.copy() # or L1[:]
L2[0] = -1
print(L1, L2) # 只有 L2 被改掉
```
----
## `enumerate`
```python=
li = [1, 2, 3, 4, 5]
for index, value in enumerate(li):
print(f"Index {index} is {value}")
```
----
## `map`、`filter`
```python=
li = [-2, 2, 3, -10, 8, -7, 1]
li = list(map(abs, li))
```
```python=
li = [-2, 2, 3, -10, 8, -7, 1]
def check_larger_than_zero(n):
return True if n > 0 else False
li = list(filter(check_larger_than_zero, li))
```
---
## `dict`
字典
對鍵值對 (key-value pair) 做一對一的對應
key 必須要 immutable (不可變動)
----
## 範例
```python=
d = {"name": "siriuskoan", "age": 19, "gender": "male"}
print(d["name"])
# solve key error
print(d.get("name"))
# 更改值
d["name"] = "phkoan"
# 新增 key
d["department"] = "CS"
# 刪除 key
del d["gender"]
```
----
## `dict` 遍歷
```python=
d = {"name": "siriuskoan", "age": 19, "gender": "male"}
for value in d.values():
print(value)
for key in d.keys():
print(key)
for k, v in d.items():
print(f"key {k} with value {v}")
```
----
## JSON
```python=
import json
json_data = """
{"name": "siriuskoan", "hobby": ["reading", "coding"]}
"""
d = json.loads(json_data)
```
---
## Function
把一塊程式碼包起來,以利後續使用及功能區分
----
## 範例
```python=
def say_hello(name):
print(f"Hello, {name}")
def add(a, b, c = 0):
return a + b + c
```
----
## Asterisks
```python=
def add(*numbers):
s = 0
for n in numbers:
s += n
return s
def mapping(**kv):
for k, v in kv.items():
print(f"{k}: {v}")
```
----
## Scope
會先從自己的 symbol table 找,找不到再去 global
```python=
g = 10
def f():
print(g)
g = 5
f()
```
```python=
g = 10
def f():
global g
print(g)
g = 5
f()
```
建議變數用傳的,不要扯到一堆 global、local 的問題
----
## `lambda`
匿名函式
```python=
INPUT = "2139023, 3242, 34.2, 23, 43".split(", ")
print(list(map(lambda x: int(x) ** 3 + 1, INPUT)))
```
----
## 遞迴
自己呼叫自己
注意終止條件及邊界處理
```python=
def fib(n):
if n == 0 or n == 1:
return 1
return fib(n - 1) + fib(n - 2)
print(fib(10))
```
---
## Module
一整份 (可能是一個或多個 python 檔案) 可以讓你引用的程式
----
## `import`
引入 python 檔案或函式庫
```python=
import math
print(math.sqrt(4))
import math as MATH
print(MATH.sqrt(4))
from math import sqrt
print(sqrt(4))
from math import sqrt as s
print(s(4))
```
----
## `import`
強烈建議不要用 `from module import *` 這種寫法
---
## virtual environment
讓開發者可以針對不同專案獨立出不同開發環境的好幫手
----
## 使用
安裝 `virtualenv` 套件
```bash
$ pip install virtualenv
```
建立新的虛擬環境
```bash
$ virtualenv venv
```
進入虛擬環境
```bash
$ .\venv\Scripts\activate
```
這時候應該會看到 prompt 前面多出 `(venv)`
----
## 使用
進到去之後,就是一個完全與外部無關的環境了
接著可以開始安裝需要的套件等等
{"metaMigratedAt":"2023-06-18T01:56:12.947Z","metaMigratedFrom":"YAML","title":"第一階段複習","breaks":true,"contributors":"[{\"id\":\"a2dd0460-a150-40b3-8024-44d3b3f2e06b\",\"add\":7007,\"del\":365}]"}