一個案例說出python的十餘個文法知識點

來源:互聯網
上載者:User

標籤:出現   知識   代碼   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的十餘個文法知識點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.