通過(guò)學(xué)習(xí)人生苦短畦娄,我學(xué)Python(二)中記錄的學(xué)習(xí)內(nèi)容又沾,我自己寫了一個(gè)簡(jiǎn)單的計(jì)算BMI值的小程序。程序的具備輸入/輸出熙卡,簡(jiǎn)單來(lái)說(shuō)就是杖刷,輸入身高和體重?cái)?shù)據(jù),程序返回BMI值和肥胖程度驳癌,第一次寫的代碼如下(貌似丑陋臃腫至極):
inputHeight = input('Please input your height(CM):')
inputWeight = input('Please input your weight(KG):')
height = float(inputHeight)
weight = float(inputWeight)
BMI = weight / ((height / 100) ** 2)
if BMI >= 32:
print('Your weight is:', weight, 'KG, ', 'and height is:', height, 'CM滑燃。')
print('Your BIM is:', round(BMI, 2), 'Your body is:', 'Severe obesity')
elif BMI >= 28:
print('Your weight is:', weight, 'KG, ', 'and height is:', height, 'CM。')
print('Your BIM is:', round(BMI, 2), 'Your body is:', 'Obesity')
elif BMI >= 25:
print('Your weight is:', weight, 'KG, ', 'and height is:', height, 'CM颓鲜。')
print('Your BIM is:', round(BMI, 2), 'Your body is:', 'Overweight')
elif BMI >= 18.5:
print('Your weight is:', weight, 'KG, ', 'and height is:', height, 'CM表窘。')
print('Your BIM is:', round(BMI, 2), 'Your body is:', 'Normal')
else:
print('Your weight is:', weight, 'KG, ', 'and height is:', height, 'CM典予。')
print('Your BIM is:', round(BMI, 2), 'Your body is:', 'Underweight')
好像,一點(diǎn)都不簡(jiǎn)潔乐严,一點(diǎn)都不優(yōu)雅...于是我把它改了改瘤袖,如下:
#定義BMIcalculator函數(shù)用于計(jì)算BMI,傳入height和weight,輸出BMI值昂验。
def BMIcalculator(height, weight):
BMI = round(weight / ((height / 100) ** 2), 2)
return BMI
#定義judgeBMI函數(shù)用于判斷肥胖程度捂敌,傳入BMI,輸出肥胖程度字符串。
def judgeBMI(BMI):
if BMI >= 32:
return 'Severe obesity'
elif BMI >= 28:
return 'Obesity'
elif BMI >= 25:
return 'Overweight'
elif BMI >= 18.5:
return 'Normal'
else:
return 'Underweight'
#輸入height和weight的值凛篙,并將其轉(zhuǎn)化為浮點(diǎn)數(shù),便于計(jì)算栏渺。
height = float(input('Please input your height(CM):'))
weight = float(input('Please input your weight(KG):'))
print('Your BMI is:', BMIcalculator(height, weight))
print('Your body is:', judgeBMI(BMIcalculator(height, weight)))
額呛梆,貌似優(yōu)雅了不少。改動(dòng)中磕诊,將整個(gè)程序的功能分成了兩塊填物,第一部分就是函數(shù)BMIcalculator(height, weight)
,用于根據(jù)身高霎终、體重計(jì)算出BMI值滞磺。第二部分,即函數(shù)judgeBMI(BMI)
莱褒,用于利用BMI值判斷肥胖程度击困,并輸出結(jié)果。
以上兩個(gè)部分在目前其實(shí)是彼此分離的广凸,包括第一個(gè)函數(shù)阅茶,也需要輸入height
和weight
兩個(gè)參數(shù)才能返回BMI,所以我們接下來(lái)需要做的就是輸入?yún)?shù)谅海,調(diào)用函數(shù)BMIcalculator(height, weight)
脸哀,得到BMI值,再將返回的BMI值作為參數(shù)調(diào)用函數(shù)judgeBMI(BMI)
扭吁,最后得肥胖程度并打印出來(lái)撞蜂。我用下面的幾行代碼來(lái)實(shí)現(xiàn)了上述的功能,其實(shí)核心就是用第一個(gè)函數(shù)的返回值做為第二個(gè)函數(shù)的參數(shù)調(diào)用第二個(gè)函數(shù):
height = float(input('Please input your height(CM):'))
weight = float(input('Please input your weight(KG):'))
print('Your BMI is:', BMIcalculator(height, weight))
print('Your body is:', judgeBMI(BMIcalculator(height, weight)))
額侥袜,這次就先到這兒蝌诡,關(guān)于這個(gè)BMI計(jì)算的程序,我會(huì)利用我在接下來(lái)學(xué)習(xí)到的東西來(lái)不斷地優(yōu)化枫吧。