this example will use:
math , class, flow control. def function, import src,
bmi.py
import bmiMethod #read data from file file = open('people.txt','r') print 'the content is ',file.name people = {} for line in file.readlines(): print 'read line:',line #rstrip = remove '\n' part = line.rstrip().split(' ') people[part[1]] = part for key in people.keys(): peolist = people.get(key) name = peolist[1] height = int(peolist[2]) weight = int(peolist[3]) bmi = bmiMethod.getBmi(height,weight) print name,"'s bmi is ",bmi peolist.append(repr(bmi)) people[key] = peolist print 'you are',bmiMethod.getRange(bmi) f = open('people2.txt','w') for key in people.keys(): listp = people.get(key) str1 = ' '.join(listp) f.write(str1+"\n") f.close()
bmiMethod.py
from __future__ import division def getBmi(height , weight): print 'height = ',height, " weight = " ,weight hei2 = float(height/100)*float(height/100) bmi =float (weight/hei2) print 'bmi = ',bmi return bmi def getRange(bmi): if bmi >= 24: return 'fat' elif bmi < 24 and bmi >= 19: return 'normal' else : return 'thin'
console
the content is people.txt read line: 1 lewis 183 70 read line: 2 leo 175 80 read line: 3 jim 170 60 read line: 4 7 170 80 read line: 5 fai 180 70 height = 183 weight = 70 bmi = 20.902385858 lewis 's bmi is 20.902385858 you are normal height = 180 weight = 70 bmi = 21.6049382716 fai 's bmi is 21.6049382716 you are normal height = 170 weight = 60 bmi = 20.7612456747 jim 's bmi is 20.7612456747 you are normal height = 170 weight = 80 bmi = 27.6816608997 7 's bmi is 27.6816608997 you are fat height = 175 weight = 80 bmi = 26.1224489796 leo 's bmi is 26.1224489796 you are fat done
people.txt
1 lewis 183 70 2 leo 175 80 3 jim 170 60 4 7 170 80 5 fai 180 70
people2.txt
1 lewis 183 70 20.902385858042937 5 fai 180 70 21.604938271604937 3 jim 170 60 20.761245674740486 4 7 170 80 27.68166089965398 2 leo 175 80 26.122448979591837
沒有留言:
張貼留言