通過學(xué)習(xí)人生苦短,我學(xué)Python(二)中記錄的學(xué)習(xí)內(nèi)容,我自己寫了一個簡單的計算BMI值的小程序。程序的具備輸入/輸出,簡單來說就是,輸入身高和體重數(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)都不簡潔,一點(diǎn)都不優(yōu)雅...于是我把它改了改,如下:
#定義BMIcalculator函數(shù)用于計算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ù),便于計算。
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)雅了不少。改動中,將整個程序的功能分成了兩塊,第一部分就是函數(shù)BMIcalculator(height, weight),用于根據(jù)身高、體重計算出BMI值。第二部分,即函數(shù)judgeBMI(BMI),用于利用BMI值判斷肥胖程度,并輸出結(jié)果。
以上兩個部分在目前其實(shí)是彼此分離的,包括第一個函數(shù),也需要輸入height和weight兩個參數(shù)才能返回BMI,所以我們接下來需要做的就是輸入?yún)?shù),調(diào)用函數(shù)BMIcalculator(height, weight),得到BMI值,再將返回的BMI值作為參數(shù)調(diào)用函數(shù)judgeBMI(BMI),最后得肥胖程度并打印出來。我用下面的幾行代碼來實(shí)現(xiàn)了上述的功能,其實(shí)核心就是用第一個函數(shù)的返回值做為第二個函數(shù)的參數(shù)調(diào)用第二個函數(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)于這個BMI計算的程序,我會利用我在接下來學(xué)習(xí)到的東西來不斷地優(yōu)化。