---
title: Week 1 - Basic Python
tags: class1000, python
description: Basic introduction of python with how to write, how functions work, etc.
---
# Week 1 - Basic Python
## 目錄
- [Anaconda 環境安裝設定](#Anaconda_環境安裝設定)
- [Jupyter lab 基本操作](#Jupyter_lab_基本操作)
- [資料型態及處理](#資料型態及處理)
- [資料結構及應用](#資料結構及應用)
- [迴圈、條件判斷](#迴圈、條件判斷)
- [撰寫我的第一個python程式](#撰寫我的第一個python程式)
- [函數撰寫](#函數撰寫)
- [例外處理](#例外處理)
- [檔案處理](#檔案處理)
- [綜合練習](#→綜合練習)
- [給你一條魚不如教你釣魚](#給你一條魚不如教你釣魚)
## Anaconda 環境安裝設定
[安裝步驟教學](https://hackmd.io/@singlien/BJtWFrbcr)
---
## Jupyter lab 基本操作
### 基本操作
- 執行單格:```shift+enter```
- 執行全部:```kernal -> Restart and run all Cells```
- 刪除單格:選取該格 -> ```dd```
- 增加縮排:選取目標 -> ```tab```
- 減少縮排:選取目標 -> ```shift+tab```
- 多行註解:選取目標 -> ```ctrl(cmd)+/```
- 查看函數說明:在該函數中 -> ```shift+tab```
### 進階操作
> https://www.jiqizhixin.com/articles/2018-05-30-5
> https://ithelp.ithome.com.tw/articles/10192614
> https://jupyter-notebook.readthedocs.io/en/stable/
---
## 資料型態及處理
### 常見資料型態
- 數值:int, float
- 字串:string
- 布林值:Boolean
- *空無:None*
### 變數宣告
```python=
test_int = 1 # int
test_float = 1.0f # float
test_str = 'string' # string
test_bool = True # boolean
```
原則:
- 可以使用任何**英文字母**,以及特殊字元底線"_"當作變數的開頭
- ==不能==使用**數字**當作開頭
- ==不能==使用空白和特殊符號("+","-")
- ==不能==使用[保留字](#查看保留字)
- 變數名稱有區分大小寫
- 命名習慣:通常使用小寫當作變數,然後底線作為分割,提高可讀性
> 箱子比喻
#### 查看保留字
```python
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
```

### 基本運算
原則:先乘除後加減

### 數值
| 數字類型 | 特色|範例 |
| -------- |---|----- |
| 整數int |有分正負號 | 1, -2, 30 |
| 浮點數float |有小數點 | 1.0, -2f, 3E+1 |
### 字串
- 使用單引號或雙引號
```python=
#使用單引號標住一段話
'Hello World'
'Hello \'World\' and \'Python\'' # \溢位字元
#使用雙引號標住一段話
"Hello 'World' and 'Python'"
```
> 練習:面對錯誤
```python=
# str1 = 'I'm ready to write python' # 會噴錯
str2_1 = 'I\'m ready to write python' # 正確
str2_2 = "I'm ready to write python" # 正確
print(str1)
print(str2_1, str2_2)
```
#### 字串運用
基本應用

進階應用
```python
# string.find(str, beg=0, end=len(string))
# 查找string中有沒有包含目標字串str,沒找到回傳-1
# ex:
>>> str1 = '123123123'
>>> str1.find(4)
-1
# string.join(seq)
# 將sequence中的目標以string串接 ex:
>>> l1 = ['a','b','c']
>>> '.'.join(l1)
a.b.c
# string.replace(old, new[, max])
# 取代指定字串
>>> str1.replace('1','4')
'423423423'
```
> https://www.runoob.com/python/python-strings.html
#### 字串索引slice ==重要==
- string[start(包含本數) : end(不含本數) : step]
```python
# 從0開始計算
>>> a = 'This is a pen.'
# 從第5個索引之後的所有元素
>>> a[5:]
'is a pen.'
# 到從後面數來第4個之前的所有元素
>>> a[:-4]
'This is a '
# 取得所有元素
>>> a
'This is a pen.'
```
### 布林值
- True or False
```python
>>> x = True
True
>>> y = False
False
>>> 1 > 2
False
>>> 1 == 1
True
```
### 型態轉換
```python
# int->str
>>> c1 = 1
>>> str(c1) # 轉換成string
'1'
# str->int
>>> s1 = '3.14'
>>> int(s1) # 轉換成int
3
# str->float
>>> s2 = '3.14e-2'
>>> float(s2)
0.0314
```
---
## 資料結構及應用
### list
特色
- 存放多個值時使用
- 可變性(元素可更改)
- List中可存放不同資料類型之物件
``` python
# ex:
>>> a = [ 1, 20.0, '3a' ] # 創建,list()
>>> a[1] = 3.14 # 修改
>>> print(a)
[1, 3.14, '3a']
```
#### list操作
基本操作==重要==
```python
>>> l1 = ['I', 'Love', 'Python']
>>> l2 = ['you','too']
# len(list)
# 回傳list長度
>>> len(l1)
3
# list.append(obj)
# 在尾端添加新對象
>>> l1.append(l2)
[ 'I', 'love', 'Python', ['you', 'too' ]]
# list.extend(seq)
# 在尾端一次添加另一序列多個值
>>> l1.extend(l2)
[ 'I', 'love', 'Python', 'you', 'too' ]
# list.insert(index, obj)
# 在指定位置插入
>>> l1.insert(1, "don't")
[ 'I', "don't" ,'love', 'Python']
# list.remove(obj)
# 移除第一個匹配項
>>> l1.remove('Python') # 同del l1[2]
[ 'I', 'love']
```
進階操作
> https://www.runoob.com/python/python-lists.html
### Tuples
特色
- 可以視為**不可改變**的串列
- 可包含不同資料型態,檢查長度,擷取元素
- <font color='red'> ==不可==修改或新增元素</font>
#### tuples操作
> https://www.runoob.com/python/python-tuples.html
### Dictionary
- 每個值(value)皆有對應的鍵(key)
- 字典的鍵(key)必須獨一無二
- 可變性(值可更改)
``` python
# ex:
>>> a = {1:'a', 2:'b', 3:'c', 4:'d'} # 創建,dict()
>>> a[1] = 'x' # 修改
>>> del a[4] # 刪除
>>> print(a)
{1: 'x', 2: 'b', 3: 'c'}
>>> print(a.keys()) # 取得keys
dict_keys([1, 2, 3])
>>> print(a.values()) # 取得values
dict_values(['x', 'b', 'c'])
```
#### dictionary操作
基本操作==重要==
```python
>>> d1 = {'Name': 'Alice', 'Age':24, 'Sex': 'Female'}
# len(dict)
# 回傳dict長度
>>> len(d1)
3
# dict.keys()
# 取得所有keys
>>> d1.keys()
dict_keys(['Name', 'Age', 'Sex'])
# dict.values()
# 取得所有values
>>> d1.values()
dict_values(['Alice', 24, 'Female'])
# dict.items()
# 取得所有(key, value)組合
# 常與for迴圈並用
>>> for k,v in d1.items():
>>> print(k,': ',v)
Name : Alice
Age : 24
Sex : Female
# dict.update(dict2)
# 把dict2的值更新到dict
>>> d2 = {'Hobby', 'Basketball'}
>>> d1.update(d2)
>>> d1
{'Name': 'Alice', 'Age': 24, 'Sex': 'Female', 'Hobby': 'Basketball'}
```
進階操作
> https://www.runoob.com/python/python-dictionary.html
### Set
- 可以視為只有keys的dictionary
- 值不可重複
#### set操作
> https://www.runoob.com/python/python-func-set.html
---
## 迴圈、條件判斷
### if_elif_else

ex:
```python=
handsome = True
rich = True
if handsome and rich:
print("I'm handsome and rich!")
elif handsome and not rich:
print("I'm handsome but not rich!")
else:
# handsome=False, rich=True or False
print("Nobody likes me QQ...")
```
### for loop
- 當有重複的事情要做的時候,可以減少重複的程式碼,讓事情事半功倍!
- **知道**總共要跑幾次

> 練習:使用for迴圈印出0-19
```python=
# 印出0-19
for i in range(20):
print(i)
```
### while loop
- **不知道**總共要跑幾次

> 練習:用while迴圈印出1-10
```python=
count=0
while True:
count+=1
print(count)
if count==10: # 拿掉就會變成無窮迴圈,電腦會當機喔!
break
```
迴圈==重要==指令
* <font color='green'>break</font>:跳出目前執行迴圈
* <font color='green'>continue</font>:略過下面程式碼,繼續執行迴圈
---
## 撰寫我的第一個python程式
- 註解:#
- 斷行:\\
- 內建函數:
- 輸出:
```print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)```
- 製作一個數字列表:
```range(start, stop[, step])```
- 有功能不會用的時候...(直接餵狗可能比較快)
```help([object])```
- 檢視物件類型
```type(object)```
> 練習:來寫一個9*9乘法表吧!
```python=
for i in range(1,10): # 1-9
for j in range(1,10):
print(str(i)+'*'+str(j)+'='+str(i*j),end='\t')
print(end='\n')
```
---
## 函數撰寫
- Functions指的是一段程式碼,被設計去執行特定工作
- 優點:
1. 可重複使用
2. 名字取的好,能讓code更容易理解
種類
* 有參數,有回傳
```python=
def blah(x):
#程式內容
return x
```
* 有參數,無回傳
```python=
def blah(x):
#程式內容
pass
```
* 無參數,無回傳
```python=
def blah():
#程式內容
pass
```
* 參數帶有預設值
> 何謂參數?何謂引數?
```python=
def test_func(a,b,c=100):# 引數
#程式內容
return a,b,c
test_func(a,b) # 呼叫函數,參數
```
ex:
> 練習:把剛剛的9*9乘法表改成函數,並且可自訂?\*?
```python=
def 乘法表製作(e):
for i in range(1,e+1): # 1-9
for j in range(1,e+1):
print(str(i)+'*'+str(j)+'='+str(i*j),end='\t')
print(end='\n')
乘法表製作(10)
```
> 練習:寫一個計算BMI的程式
```python=
def calculate_bmi(weight, height):
# weight in kg
# height in cm
bmi = weight / (height/100)**2
return bmi
```
---
## 例外處理
```python
try:
# Do something,試試看
pass
except Exception as e:
# Oops! Something went wrong...,出錯了才執行
pass
finally:
# Do it, no matter right or wrong,不管對或錯都會執行
pass
```
進階操作
> https://www.runoob.com/python/python-exceptions.html
---
## 檔案處理
基本操作
- 開啟檔案
```open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
- mode:
- r :讀取
- w :寫入
- a :追加
- b :二進位
- 關閉檔案:+1::+1::100:==一定要記得==
```file.close()```
- 讀取內容
``` file.read(size=未設定則全部讀取)```
- 逐行讀取
``` file.readline()```
- 寫入內容
``` file.write(string)```
> 讀取檔案的兩種寫法
```python
# 方法一
# 特色:直覺、好懂
# 缺點:一定要呼叫關閉函數
f = open('filepath', mode='r', encoding='utf-8')
texts = f.read() # 讀取文字,並存成變數texts
# texts 型態為str,可以拿來進行其他處理,詳見string處理方法
f.close() # 關閉檔案,非常重要
# 方法二
# 特色:不用呼叫關閉函數、程式碼簡單
with open('filepath', mode='r', encoding='utf-8') as f:
texts = f.read()
# texts 型態為str,可以拿來進行其他處理,詳見string處理方法
```
---
## →綜合練習
> 讀取檔案['Python wiki.txt'](https://drive.google.com/open?id=1tY5LRAUtJsULHQ4GO1lAsSoAxlPAlL4d),把Python改成Go,然後輸出成'Go wiki.txt'
> 檢查:應該要出現20個'Go'
```python=
# 開啟檔案,讀取模式
try:
f = open('python wiki.txt','r',encoding='utf-8')
t = f.read() # 讀取所有內容
except Exception as e:
print(e)
finally:
f.close() # 關閉檔案
# 用with就不用呼叫.close()
# 開啟檔案,寫入模式,不存在則創一個新的
with open('go wiki.txt', 'w', encoding='utf-8') as f:
f.write(t.replace('Python', 'Go')) # 寫入內容
```
進階操作
> https://www.runoob.com/python/file-methods.html
---
## 給你一條魚不如教你釣魚
有問題的時候該怎麼辦呢?去找這些參考資料GO!
(直接餵狗!懂?)
> [Basic Python tutorial](https://www.runoob.com/python3/python3-tutorial.html)
> [Pandas tutorial](https://pandas.pydata.org/pandas-docs/stable/)
> [Numpy tutorial](https://docs.scipy.org/doc/numpy/reference/)
> [HTML tutorial](https://www.w3schools.com/html/)
>
> [下一篇請點此:Week 2 - Pandas](https://hackmd.io/@singlien/H14nC3fqS)
>
---
# Q&A 總整理
1. 何時使用(), [], {}?
* ()使用時機:
* 呼叫/建立函數
* 使用tuple資料結構
* []使用時機:
* slice
* 使用list資料結構
* {}使用時機:
* 使用dict資料結構
2. list與dict差別
* list:
* 有序的資料結構
* 依照「位置」索引元素
* dict:
* 無序的資料結構
* 依照「鍵值」索引元素
3. 檔案處理時為何讀取與寫入要分開寫?
* ```open()```函數一次只能擇一處理讀\(r\)或寫(w),不能同時又讀又寫