以下是一个用Python编写的BMI计算器的示例代码:
def calculate_bmi(weight, height, method="metric"):
if method == "metric":
bmi = weight / (height ** 2)
elif method == "imperial":
bmi = (weight * 703) / (height ** 2)
else:
raise ValueError("Invalid method. Please choose either 'metric' or 'imperial'.")
return bmi
def check_bmi_category(bmi):
if bmi < 18.5:
category = "Underweight"
elif bmi < 24.9:
category = "Normal weight"
elif bmi < 29.9:
category = "Overweight"
else:
category = "Obese"
return category
def main():
weight = float(input("Enter your weight in kg or pounds: "))
height = float(input("Enter your height in meters or inches: "))
method = input("Enter the method of measurement (metric/imperial): ")
try:
bmi = calculate_bmi(weight, height, method)
category = check_bmi_category(bmi)
print("Your BMI is: {:.2f}".format(bmi))
print("Category: {}".format(category))
except ValueError as e:
print(e)
if __name__ == "__main__":
main()
这个示例代码包含了一个calculate_bmi
函数,用于计算BMI值,以及一个check_bmi_category
函数,用于根据BMI值确定体重类别。在main
函数中,用户可以输入体重、身高和测量方法来计算他们的BMI值,并打印出结果和体重类别。
在输入中,用户需要输入正确的测量方法,即"metric"(公制)或"imperial"(英制)。如果输入了其他方法,代码将引发ValueError
并打印错误消息。
这个示例代码可以通过多种方法进行扩展和改进,例如添加更多的体重类别、提供更多的测量方法选项、增加输入验证等等。
上一篇:BMI计算器图形用户界面