Files
bmi-calculator/bmi.py

67 lines
1.9 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.
"""BMI 计算器(命令行版)
输入:身高(cm)、体重(kg)
输出:BMI 值及分类
分类阈值采用中国标准 WS/T 428-2013:
< 18.5 偏瘦
18.5~24 正常
24~28 超重
>= 28 肥胖
"""
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) -> tuple[str, str]:
"""按中国标准 (WS/T 428-2013) 返回 (分类, 提示)。"""
if bmi < 18.5:
return "偏瘦", "建议适当增加能量与蛋白质摄入,并排查消瘦原因。"
elif bmi < 24.0:
return "正常", "体重处于健康范围,保持即可。"
elif bmi < 28.0:
return "超重", "建议控制总热量,增加有氧与力量训练。"
else:
return "肥胖", "建议就医或咨询营养师,制定减重方案。"
def read_number(prompt: str, lo: float, hi: float) -> float:
"""读取一个区间内的数字,输入非法时重新询问。"""
while True:
raw = input(prompt).strip()
try:
value = float(raw)
except ValueError:
print(" ✗ 请输入数字,例如 180 或 65.5")
continue
if not lo <= value <= hi:
print(f" ✗ 数值应在 {lo} ~ {hi} 之间")
continue
return value
def main() -> None:
print("=" * 38)
print(" BMI 计算器(中国标准)")
print("=" * 38)
height = read_number("请输入身高 (cm):", 50, 250)
weight = read_number("请输入体重 (kg):", 10, 300)
bmi = calc_bmi(height, weight)
category, advice = classify(bmi)
print("-" * 38)
print(f"身高:{height:.1f} cm 体重:{weight:.1f} kg")
print(f"BMI :{bmi:.1f} → {category}")
print(f"提示:{advice}")
print("-" * 38)
if __name__ == "__main__":
main()