標籤:出現 知識 代碼 rip 異常處理 else min 傳遞 fas
典型代碼:
1、注釋
2、函數調用
3、帶參數的函數傳回值
4、無傳回值的return語句
5、字典變數的賦值和使用
6、txt檔案讀取
7、檔案變數
8、異常處理
9、輸出結果
10、列表排序
11、字串分割
12、Null 字元處理
13、判斷
14、迴圈
這是一個典型案例代碼
def sanitize(time_string): #函數定義及實參傳遞
if ‘-‘ in time_string: #判斷一個字串中是否存在‘-‘支付;判斷語句
splitter = ‘-‘
elif ‘:‘ in time_string: #elif語句
splitter = ‘:‘
else: #else語句
return(time_string) #帶參數的函數返回語句
(mins,secs) = time_string.split(splitter) #多個變數的自動賦值,字串分割
return(mins+‘.‘+secs) #參數計算後的函數返回語句
def get_coach_data(filename):
try: #先嘗試
with open(filename) as f: #開啟檔案
data = f.readline() #按行讀取檔案內容並送至變數data中
templ = data.strip().split(‘,‘) #取消Null 字元,字串分割
return({‘name‘:templ.pop(0), #字典變數的賦值,
‘dob‘:templ.pop(0),
‘times‘:str(sorted(set([sanitize(t) for t in templ]))[0:3])}) #排序、迴圈、取前3個字元內容
except IOERROR as ioerr:· #出現異常後的異常處理語句
print(‘File error:‘+str(ioerr))
return(None)
james = get_coach_data(‘james2.txt‘) #檔案變數
print(james[‘name‘]+"‘s fasttest times are "+james[‘times‘]) #輸出
一個案例說出python的十餘個文法知識點