Skip to content

Instantly share code, notes, and snippets.

@fkztw
Last active December 14, 2015 17:49
Show Gist options
  • Save fkztw/5124618 to your computer and use it in GitHub Desktop.
Save fkztw/5124618 to your computer and use it in GitHub Desktop.
投影片 http://j.mp/mosky-pwp (後來上課後講者有稍做修改 所以可能不太一樣)
pipy - commit your python project
project - a blog system
Dynamic typing, Static typing, Functor, Closure 我還不熟的東西
Python 2 or 3 ?
2.7 是 2.x 最後一個 release
python 目前全力投入 3.x 的開發
3.x is easier for newcomer
2.x has more third-party lib
2to3.py (官方) 3to2.py(非官方) 可以轉換 syntax
2.x 有 backported features 因為和 3.x 平行開發
所以會把 3.x 的一些 featurs 拿回來用
Use Python 3 if you can. 用 python3 就對了(?
根據你要用的 library 選擇 2.x 或 3.x
課程會以 python2.7 為主, 但會介紹 3.x 中的改變
一般看到的都是 cpython , 對 c/c++ 提供較好的相容性,
可以在 c/c++ 中寫 python 的 module, 然後在 python 中 import 進來
主流都是用 cpython, 一般的 document 也都是以 cpython 為主
byte code
Python Shell
-c 直接執行一行式
python -c 'print "hello, world"' #python2
python -c 'print("hello, world")' #python3
-m 使用module
python -m SimpleHTTPServer [port] #python2
python -m http.server [port] #python3
hello.py
用4個空白 不要用tab
: 是一個block開始的意思
換行就代表一個statement的結束
__name__ : the name of module
if __name__ == '__main__': #類似c裏面的main函數
common types
Characteristics
Mutable / Immutable (是否可變動)
Immutable 不可變動
ex: Hashable (__hash__)
python 的變數可視為純pointer
Immutable 代表該變數指向的物件是不可變動的
Ordered / Unordered
Iterable (__iter__)
Numeric (Immutable, Hashable)
integer
float
long
complex
1+1j 小寫或大寫都可以
boolean
True, False 開頭要大寫
Sequence (Iterable, Ordered, Mutable/Immutable)
string
Mapping
dictionary
Set
a = 'string'
1. 先建立 string 這個 object
2. 再建立 a 這個 pointer
3. 再把 a 指向 string
所以 string 是 Immutable
但可以讓 a 指向其他的 object
Interger, Float and Long
divmod(被除數, 除數) -> 回傳商數和餘數(tuple)
5//2 -> 取商的 floor
5**0.5 -> **0.5 就是取 square root
bin(整數) -> 可以將該整數以 binary 表示
float(整數) -> 可以將該整數轉成 float 表示
Complex
complex(0,1) -> 0+1j
a = 3.0 + 4.0j
a.real -> 3.0
a.imag -> 4.0
abs(a) -> 算出該複數在複數平面上跟原點的距離
等同於 sqrt(a.real**2 + a.imag**2)
Boolean
not False (在python中直接打not就好)
True and False (在python中直接打and就好)
True or False (在python中直接打or就好)
False 的值就是 0 -> False+1 == 1
True 的值就是 1 -> True+1 == 2
python裏面的float有做過處理 所以 10 == 10.0 是 True
x is y -> 判斷 x 和 y 是否相同
String and Unicode
python 的單引號和雙引號是一樣的意思
String (immutable seq.) -> python 中的字串是不能更改的
r'字串\n' -> r 代表 raw string 裏面的跳脫字元不會被轉譯
'''字串''' -> 多行字串 (會幫你紀錄換行符) -> 通常python裏面的多行註解也是這樣寫
Unicode (Immutable seq.)
u'字串' -> 代表裏面存的編碼是unicode
ur'字串' -> 代表 raw string 裏面存的編碼是unicode
ur 的順序是固定的 不可以寫成 ru
u'''字串''' -> 代表裏面存的編碼是unicode
ord(字元) -> 將字元轉成 ascii
chr(ascii編碼) -> 將 ascii 編碼轉成字元
unichr(unicode編碼) -> 將 unicode 編碼轉成 unicode 字串
Decoding (str -> unicode)
'中文'.decode('utf-8') == unicode('中文', 'utf-8')
Encoding (unicode -> str)
u'中文'.encode('utf-8')
python2 設計的時候沒有考慮到 unicode 的問題
python3 的 str 就是 unicode
新的型態 bytes (Immutable seq.)
常用 method
decode, encode, endswith, find, format, join, lower, partition,
replace, split, startwith, strip, upper
詳細的 method 請參見 python 的 doc
string formatting
modulo (%)
%r -> representation
'Hello, %s' % name -> 用 name 的內容取代 %s
str.format
{}
List and tupleple
List (Mutable seq.) Tuple (Immutable seq.)
[] tuple()
['item'] ('item', ) -> 只有一個的情況下要加逗點
兩者的元素都可以放不同的型態
List 在 python 中的實作是用 array, 所以會比較慢
Sequence
Immutable seq. 支援的操作
x in s -> 查 s 是不是在 x 裏面, 結果會回傳 boolean
x not in s 搜尋是用 linear search, 效能上要注意一下
s + t
s * n
slice
string.len()
string.index(a) -> 如果沒找到a的話會跳出 except 的訊息
string.count(a) -> 計算 string 裏面 a 出現幾次
Mutable seq. 支援的操作
s[1] = x
s[i:j] = t
del s[i:j]
s[i:j:k]
s.append(x)
s.insert(i,x)
s.pop([i])
s.remove(x)
s.extend(x) -> 擴充 s
s.append(x) -> 將 x 加進去變成元素
in-place
s.sort() -> 內建的 sort 是 tim sort, 是個改良板的 merge sort
s.reverse() -> 把 seq. 顛倒過來
Sequence 支援 比較 的動作
Slicing and slice
s[:] # a copy of the whole array
Mapping
Dictionary (Mutable map)
就是 key-value pairs
{'A':1, 'B':2, 'C':3}
dict(A=1, B=2, C=3)
實作是用 B tree 所以不會照順序,
如果要照順序的話可以用 collection 的 ordered dictionary
或是把 key 存在一個list裏面
zip()
k = 'ABC'
v = [1,2,3]
pairs = zip(k,v)
# pairs 會變成 [('A', 1), ('B', 2), ('C', 3)]
# dict(pairs) 是 {'A': 1, 'C': 3, 'B': 2}
dictionary 可以不用 string 當 key, list 就不行
支援的操作 (k is the name of key)
len(d)
d[k]
d[k] = v (Mutable)
del d[k]
k in d, k not in d
d.copy()
d.get(key[, default])
d.setdefault(key[, default])
d.items(), d.keys(), d.values() #在 python3 裏面這3個函式回傳的都是 iter 不是 list
d.pop(key[, default])
d.update([other])
d.update(dict(...))
None -> 是個 object, 有點類似 c 裏面的 NULL
可以在用 python 先簡單寫出演算法並證明自己的想法, 再用 C 去實作出來
Set (mutable set)
set() #python2
set('ABC') == set(['A', 'B', 'C'])
{'A', 'B', 'C'} #python3
# s 代表 set
len(s)
x in s, x not in s
s.add(elem)
s.discard(elem)
s.pop()
s |= other
s &= other
s | other
s & other
Flow Control
注意冒號和縮排
if-else
if [condition 1]:
elif [condition 2]:
else:
被視為 False 的值
None
False
Zeros (0, 0.0, 0L, 0j)
Empty containers ('', [], {})
__nonzero__() or __len__() return 0 or False
注意: if [0]: 和 if [[]]: 後的敘述會被執行
因為 [] 裏面有包含東西就不會被視為空的
() 和 {} 也是同樣的道理
for (for-each 的性質, python 裏面只有這種for)
for [item] in [iterable]:
for i in range(3): -> 會建個 list 出來, 比較浪費資源
for i in xrange(3): -> xrange 只會建個 iter, 比較節省資源
# python3 沒有 xrange(), 因為 python3 的 range() 就是 python2 的 xrange()
# python3 裏面把很多東西都改成比較節省資源的方式
for i, item in enumerate(sth):
print i, item
-> i 會是從0開始的index, item 就是 sth 裏面的 element
python 的 for 可以 iterate all of iterable object
iter(sth) -> 可以把 sth 轉成 iter 後回傳
while
task = [...]
while task:
...
當 tasks 變成 empty 的時候就跳出迴圈
break, continue (都只能用在 loop 裏面)
就跟 C 一樣,
可能可以讓 python 執行的更快
因為python是 interpretation
提前結束的話可以少跑一些程式
所以 python 鼓勵使用 break 和 continue
The else Clause on Loops
loops:
...
else:
上面的迴圈如果沒有被 break 提前結束的就會進入 else
可以用來取代平常設定的 flag
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment