TQC+ 程式語言Python 904 資料計算
第9類:檔案與異常處理

TQC+ 程式語言Python 904 資料計算

題目說明:

請撰寫一程式,讀取read.txt(每一列的格式為名字和身高、體重,以空白分隔)並顯示檔案內容、所有人的平均身高、平均體重以及最高者、最重者。
提示:輸出浮點數到小數點後第二位。

範例輸出

Ben 175 65

Cathy 155 55

Tony 172 75
Average height: 167.33
Average weight: 65.00
The tallest is Ben with 175.00cm
The heaviest is Tony with 75.00kg
 

檔案下載:
read.txt


程式碼:

data = []

with open("read.txt","r") as file:
   for line in file:
       print(line)
       data.append(line.split())

name = [data[n][0] for n in range(3)]
height = [eval(data[h][1]) for h in range(3)]
weight = [eval(data[w][2]) for w in range(3)]

print('Average height: %.2f' %(sum(height) / 3))
print('Average weight: %.2f' %(sum(weight) / 3))
print('The tallest is %s with %.2fcm' %(name[height.index(max(height))], max(height)))
print('The heaviest is %s with %.2fkg' %(name[weight.index(max(weight))], max(weight)))

TQC+ 程式語言Python 第9類:檔案與異常處理





如果覺得文章內容還不錯的話,麻煩請幫我點個讚!感謝

可以多點幾次喔~~

第一次點讚需使用 Google 或 Facebook 帳號註冊

發表迴響