28. 28
流程控制
■ 條件執行
● if: … elif: … else: …
■ 迴圈
● for in: … else: …
■ break
■ continue
■ 常搭配 xrange() 使用
● while: … else: …
if (v is True) and (w is True):
# 當 v 與 w 為 True 時執行
elif x is not True:
# 當 x 不為 True 時執行
else:
# 當 v 與 w 不為 True 且 x 為 True
for e in c:
# 對 c 中的所有元素 e 進行作業
else:
# 迴圈結束後執行
while a != b:
# 對 a 與 b 的值仍相異時執行
else:
# 迴圈結束後執行
31. 31
資源管理員 (cont.)
■ 大多數內建的資源物件都有支援
● open()
● threading.Lock(), thread.allocate_lock()
try:
# 取得資源並使用
fp = open(“f.txt”, “r”)
...
finally:
# 釋放資源
fp.close()
with open(“f.txt”, “r”) as fp:
# 使用資源
...
with open(...) as fp, w_lock:
# 使用資源
...
32. 32
程式模組
■ 將程式碼分門別類放置在不同檔案
■ 使用 import 關鍵字進行匯入
● import my_module as m
■ 也可放在資料夾中
● 資料夾中必須有 __init__.py 檔案存在
● import my_package.my_module as m
■ 搜尋時是利用 sys.path 串列內容依序找尋
33. 33
常用關鍵字
■ A in B
● 元素 A 是否存在於容器 B 中
■ A is B
● 物件 A 與物件 B 是否為相同的參考
● 多用在判斷是否為 None, True, False
■ pass
● 空指令
● 填充程式碼區段使之滿足語法需求
■ not, and, or
● 邏輯運算