通過學習人生苦短,我學Python(二)中記錄的學習內容,我自己寫了一個簡單的計算BMI值的小程序。程序的具備輸入/輸出,簡單來說就是,輸入身高和體重數據,程序返回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')
好像,一點都不簡潔,一點都不優雅...于是我把它改了改,如下:
#定義BMIcalculator函數用于計算BMI,傳入height和weight,輸出BMI值。
def BMIcalculator(height, weight):
BMI = round(weight / ((height / 100) ** 2), 2)
return BMI
#定義judgeBMI函數用于判斷肥胖程度,傳入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的值,并將其轉化為浮點數,便于計算。
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)))
額,貌似優雅了不少。改動中,將整個程序的功能分成了兩塊,第一部分就是函數BMIcalculator(height, weight)
,用于根據身高、體重計算出BMI值。第二部分,即函數judgeBMI(BMI)
,用于利用BMI值判斷肥胖程度,并輸出結果。
以上兩個部分在目前其實是彼此分離的,包括第一個函數,也需要輸入height
和weight
兩個參數才能返回BMI,所以我們接下來需要做的就是輸入參數,調用函數BMIcalculator(height, weight)
,得到BMI值,再將返回的BMI值作為參數調用函數judgeBMI(BMI)
,最后得肥胖程度并打印出來。我用下面的幾行代碼來實現了上述的功能,其實核心就是用第一個函數的返回值做為第二個函數的參數調用第二個函數:
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)))
額,這次就先到這兒,關于這個BMI計算的程序,我會利用我在接下來學習到的東西來不斷地優化。