Files

189 lines
5.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.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""命令行交互式 BMI / 每日热量 / 七大营养素计算器。
运行:python bmi_cli.py
菜单按数字选择,输入 0 退出。
"""
ACTIVITY_FACTORS = {
"1": ("久坐(几乎不运动)", 1.2),
"2": ("轻度活动(每周 1–3 次)", 1.375),
"3": ("中度活动(每周 3–5 次 / 约 1 万步)", 1.55),
"4": ("高强度活动(每周 6–7 次)", 1.725),
"5": ("极高强度(体力劳动 / 专业训练)", 1.9),
}
VITAMINS = [
("维生素 A", "800 μg RAE(女 700)"),
("维生素 D", "10 μg"),
("维生素 E", "14 mg α-TE"),
("维生素 C", "100 mg"),
("维生素 B1", "1.4 mg(女 1.2)"),
("维生素 B2", "1.4 mg(女 1.2)"),
("叶酸", "400 μg DFE"),
]
MINERALS = [
("钙", "800 mg"),
("铁", "12 mg(女 18)"),
("锌", "12.5 mg(女 7.5)"),
("镁", "330 mg(女 300)"),
("钾", "2000 mg"),
("钠", "< 2000 mg(盐 < 5 g)"),
("碘", "120 μg"),
]
def read_float(prompt, minimum=None):
"""读取浮点数,minimum 为允许的最小值。"""
while True:
raw = input(prompt).strip()
try:
value = float(raw)
except ValueError:
print(" × 请输入数字。")
continue
if minimum is not None and value < minimum:
print(f" × 请输入不小于 {minimum} 的数值。")
continue
return value
def read_gender():
while True:
g = input("性别(男/女): ").strip()
if g in ("男", "女"):
return g
print(" × 请输入“男”或“女”。")
def read_activity():
print("活动量:")
for key, (name, factor) in ACTIVITY_FACTORS.items():
print(f" {key}) {name} [系数 {factor}]")
while True:
choice = input("选择活动量编号: ").strip()
if choice in ACTIVITY_FACTORS:
return ACTIVITY_FACTORS[choice]
print(" × 无效编号,请重新选择。")
def read_body():
height = read_float("身高(cm): ", 50)
weight = read_float("体重(kg): ", 10)
age = read_float("年龄(岁): ", 1)
gender = read_gender()
return height, weight, age, gender
def calc_bmi(height_cm, weight_kg):
h = height_cm / 100.0
return weight_kg / (h * h)
def classify_bmi(bmi, standard="cn"):
if standard == "cn":
table = [(18.5, "偏瘦"), (24.0, "正常"), (28.0, "超重"), (float("inf"), "肥胖")]
else:
table = [(18.5, "偏瘦"), (25.0, "正常"), (30.0, "超重"), (float("inf"), "肥胖")]
for limit, label in table:
if bmi < limit:
return label
def calc_bmr(gender, weight_kg, height_cm, age):
base = 10 * weight_kg + 6.25 * height_cm - 5 * age
return base + 5 if gender == "男" else base - 161
def healthy_weight_range(height_cm):
h = height_cm / 100.0
return round(h * h * 18.5, 1), round(h * h * 24.0, 1)
def menu_bmi():
print("\n== 计算 BMI ==")
height, weight, _, _ = read_body()
bmi = calc_bmi(height, weight)
low, high = healthy_weight_range(height)
print(f"\n 身高 {height:.0f} cm | 体重 {weight:.1f} kg")
print(f" BMI = {bmi:.2f}")
print(f" 中国标准:{classify_bmi(bmi, 'cn')} | WHO 标准:{classify_bmi(bmi, 'who')}")
print(f" 健康体重区间(中国标准):{low} ~ {high} kg")
def menu_tdee():
print("\n== 估算每日所需热量 ==")
height, weight, age, gender = read_body()
name, factor = read_activity()
bmr = calc_bmr(gender, weight, height, age)
tdee = bmr * factor
print(f"\n 基础代谢 BMR ≈ {bmr:.0f} kcal")
print(f" 活动量:{name}(系数 {factor})")
print(f" 每日总消耗 TDEE ≈ {tdee:.0f} kcal")
print(" --- 参考 ---")
print(f" 减重:{tdee - 500:.0f} ~ {tdee - 300:.0f} kcal/天")
print(f" 维持:{tdee:.0f} kcal/天")
print(f" 增重:{tdee + 300:.0f} ~ {tdee + 500:.0f} kcal/天")
def menu_nutrients():
print("\n== 七大营养素摄入建议 ==")
height, weight, age, gender = read_body()
_, factor = read_activity()
bmr = calc_bmr(gender, weight, height, age)
tdee = bmr * factor
calories = tdee
if input("是否按减重调整?(y/N): ").strip().lower() == "y":
calories = tdee - 400
carb = calories * 0.51 / 4
protein = max(calories * 0.22 / 4, 1.4 * weight)
fat = calories * 0.27 / 9
water = 1700 if gender == "男" else 1500
print(f"\n 日均总热量目标 ≈ {calories:.0f} kcal")
print(" ----------------------------------------")
print(f" 1) 碳水化合物 : {carb:.0f} g (约占 51% 能量)")
print(f" 2) 蛋白质 : {protein:.0f} g (≥1.4 g/kg 体重)")
print(f" 3) 脂肪 : {fat:.0f} g (约占 27% 能量)")
print(f" 4) 维生素 : 见下表(按 DRIs)")
print(f" 5) 矿物质 : 见下表(按 DRIs)")
print(f" 6) 水 : {water} ml")
print(f" 7) 膳食纤维 : 25–30 g")
print("\n [维生素]")
for name, val in VITAMINS:
print(f" {name:<10} {val}")
print("\n [矿物质]")
for name, val in MINERALS:
print(f" {name:<10} {val}")
def main():
print("\n" + "=" * 40)
print(" BMI / 热量 / 营养素 命令行计算器")
print("=" * 40)
while True:
print("\n1) 计算 BMI")
print("2) 估算每日所需热量")
print("3) 七大营养素摄入建议")
print("0) 退出")
choice = input("请选择 > ").strip()
if choice == "1":
menu_bmi()
elif choice == "2":
menu_tdee()
elif choice == "3":
menu_nutrients()
elif choice in ("0", "q", "quit", "exit"):
print("已退出,祝你健康!")
break
else:
print(" × 无效选择,请重新输入。")
if __name__ == "__main__":
main()