You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何从try-except定义变量?BMI计算器遇NameError

问题原因

你写的height_main()和weight_main()是两个用来获取身高、体重的函数,但你从来没调用过它们,而且函数内部的height、weight都是局部变量,不会自动跑到全局作用域里。所以当你执行bmi = weight / (height**2)时,Python找不到这两个变量,就报了NameError。

另外你的代码还有两个小问题:

  • 输入负数时,else分支里的("Please enter a valid height.")只是个没用的字符串,没加print(),用户看不到错误提示
  • 函数里初始设height = 0然后height += height_try完全没必要,直接把有效输入赋值给height就行
修正后的代码
def get_height():
    while True:
        try:
            height = float(input("Enter your height in meters: "))
        except ValueError:
            print("Please enter a valid height.")
            continue
        if height > 0:
            return height
        else:
            print("Please enter a valid height.")

def get_weight():
    while True:
        try:
            weight = float(input("Enter your weight in kilograms: "))
        except ValueError:
            print("Please enter a valid weight.")
            continue
        if weight > 0:
            return weight
        else:
            print("Please enter a valid weight.")

# 调用函数,把返回值赋值给变量
height = get_height()
weight = get_weight()

bmi = weight / (height ** 2)
print(f"Your BMI is: {bmi:.2f}")
关键说明
  • 必须调用函数并接收返回值:height = get_height()、weight = get_weight(),这样全局作用域里才有这两个变量
  • 简化了函数逻辑:去掉了多余的初始变量赋值,直接在验证通过后返回有效输入
  • 补全了负数输入时的print语句,用户能收到错误提示
  • 最后输出BMI时用了格式化字符串,结果更友好

内容的提问来源于stack exchange,提问作者Zerachiel Violet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 02:52:12