Files

80 lines
2.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""BMI 计算器
运行:python bmi.py
公式:BMI = 体重(kg) / 身高(m)^2
"""
def calc_bmi(height_cm: float, weight_kg: float) -> float:
"""根据身高(cm)、体重(kg)计算 BMI"""
height_m = height_cm / 100
return weight_kg / (height_m ** 2)
def classify(bmi: float, standard: str = "CN") -> str:
"""按标准划分等级,standard='CN' 中国标准 / 'WHO' 国际标准"""
if standard == "CN": # 中国标准 WS/T 428-2013
if bmi < 18.5:
return "偏瘦"
elif bmi < 24.0:
return "正常"
elif bmi < 28.0:
return "超重"
else:
return "肥胖"
else: # WHO 国际标准
if bmi < 18.5:
return "偏瘦"
elif bmi < 25.0:
return "正常"
elif bmi < 30.0:
return "超重"
else:
return "肥胖"
def healthy_weight_range(height_cm: float, low: float = 18.5, high: float = 23.9):
"""返回该身高下“正常 BMI”对应的体重区间(kg)"""
h = height_cm / 100
return low * h * h, high * h * h
def main():
print("=== BMI 计算器 ===")
while True:
try:
height = float(input("请输入身高(厘米,如 165):"))
weight = float(input("请输入体重(公斤,如 52):"))
except ValueError:
print("输入有误,请输入数字。\n")
continue
if not (50 < height < 250) or not (10 < weight < 500):
print("数值超出合理范围,请重新输入。\n")
continue
bmi = calc_bmi(height, weight)
level = classify(bmi, "CN")
w_low, w_high = healthy_weight_range(height)
print(f"\n您的 BMI = {bmi:.1f}")
print(f"中国标准评级:{level}")
print(f"WHO 标准评级:{classify(bmi, 'WHO')}")
print(f"该身高正常体重区间:{w_low:.1f} ~ {w_high:.1f} kg")
if bmi < 18.5:
print(f"提示:距正常下限还差约 {w_low - weight:.1f} kg,"
f"建议适当增加热量与蛋白质摄入。")
elif bmi >= 24:
print(f"提示:超出正常上限约 {weight - w_high:.1f} kg。")
else:
print("提示:体重在正常范围内。")
if input("\n是否再算一次?(y/n):").lower() != "y":
break
print()
if __name__ == "__main__":
main()