使用Plotly Dash开发BMI计算器遇UnboundLocalError问题求助
问题分析
错误UnboundLocalError: local variable 'bmi' referenced before assignment的核心原因是:回调函数update_output_div仅在体重为磅+身高为英尺、体重为公斤+身高为米这两种特定组合下给bmi赋值。当用户选择其他单位组合(比如磅+米、公斤+英尺)时,bmi变量从未被定义,直接return就会触发未绑定变量的错误。
解决方案
有两种可靠的修复思路:
思路1:初始化兜底值,避免变量未定义
在函数开头给bmi设置默认值,确保无论什么输入情况都有值返回:
def update_output_div(weight, weight_unit, height, height_unit): bmi = "请检查单位组合或输入值" # 初始化默认提示 if weight_unit == 'lbs' and height_unit == 'ft': bmi = 703 * (weight/(height * 12)**2) elif weight_unit == 'kgs' and height_unit == 'm': bmi = weight/(height**2) # 对数值结果保留两位小数,提示文本直接返回 return round(bmi, 2) if isinstance(bmi, float) else bmi
思路2:统一单位转换,覆盖所有组合
先把所有输入单位转换为国际标准单位(公斤+米),再统一计算BMI,这种方式更健壮,支持任意单位组合:
def update_output_div(weight, weight_unit, height, height_unit): # 体重转公斤 weight_kg = weight * 0.453592 if weight_unit == 'lbs' else weight # 身高转米 height_m = height * 0.3048 if height_unit == 'ft' else height # 计算BMI bmi = weight_kg / (height_m ** 2) return round(bmi, 2)
修改后的完整代码
以下是采用思路2的可运行完整代码:
from dash import Dash, dcc, html, Input, Output app = Dash(__name__) app.layout = html.Div([ html.H1("BMI Calculator"), html.Div([ html.H2('Enter your weight'), dcc.Input(id='weight', value=160, type='number'), dcc.RadioItems( options=[{'label': 'pounds', 'value': 'lbs'}, {'label': 'kilograms', 'value': 'kgs'}], value='lbs', id='weight_unit' ), html.H2('Enter your height'), dcc.Input(id='height', value=5.83333333, type='number'), dcc.RadioItems( options=[{'label': 'feet', 'value': 'ft'}, {'label': 'meters', 'value': 'm'}], value='ft', id='height_unit' ), ]), html.Br(), html.H1("Your estimated body mass index is:"), html.H1(id='bmi'), ]) @app.callback( Output(component_id='bmi', component_property='children'), Input(component_id='weight', component_property='value'), Input(component_id='weight_unit', component_property='value'), Input(component_id='height', component_property='value'), Input(component_id='height_unit', component_property='value'), ) def update_output_div(weight, weight_unit, height, height_unit): weight_kg = weight * 0.453592 if weight_unit == 'lbs' else weight height_m = height * 0.3048 if height_unit == 'ft' else height bmi = weight_kg / (height_m ** 2) return round(bmi, 2) if __name__ == '__main__': app.run_server(debug=True)
内容的提问来源于stack exchange,提问作者rerecodes
相关产品推荐
相关产品推荐

