UnboundLocalError: local variable 'bmi' referenced before assignment line 38

Question:

I am making a BMI calculator with plotly Dash. I’m trying to code it where the user choses the unit of the input for weight and height, however its throwing an error on line 38:

UnboundLocalError: local variable ‘bmi’ referenced before assignment

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):
    if weight_unit == 'lbs' and height_unit == 'ft':
        bmi = 703 * (weight/(height * 12)**2)
    if weight_unit == 'kgs' and height_unit == 'm':
        bmi = (weight)/((height)**2)
    return bmi 

if __name__ == '__main__':
    app.run_server(debug=True)

Asked By: rerecodes

||

Answers:

Using return on a variable that was assigned within an if block means that the variable will only be assigned if that condition is met. Otherwise, when the code doesn’t run, the variable bmi does not get defined, and cannot be returned.

To resolve the problem, one way is to assign a value before the if statement.

def update_output_div(weight, weight_unit, height, height_unit):
    bmi = None
    if weight_unit == 'lbs' and height_unit == 'ft':
        bmi = 703 * (weight/(height * 12)**2)
    if weight_unit == 'kgs' and height_unit == 'm':
        bmi = (weight)/((height)**2)
    return bmi 
Answered By: ARK1375