Skip to content
Advertisement

Why can’t I use my local variable despite already returning it?

It says I haven’t defined the variable even though the code that does that is literally right above it, the error message appears:

“Traceback (most recent call last): File “main.py”, line 55, in if kategoribmi == “underweight”: NameError: name ‘kategoribmi’ is not defined”

    if kelas == "('15', 'P')":
      if bmi > 28.2:
        kategoribmi = "obese"
      elif bmi >= 23.6 < 28.2:
        kategoribmi = "overweight"
      elif bmi <= 15.8:
        kategoribmi = "underweight"
      else:
        kategoribmi = "ideal"


    if kategoribmi == "underweight":
      underweight()
    elif kategoribmi == "overweight":
      overweight()
    elif kategoribmi == "obese":
      obese()
    else:
      ideal()

I’m really unsure what to do here, I’ve tried looking up how to fix this but I’m still unclear.

Advertisement

Answer

This happens because when the compiler checks your code, it cannot be sure whether the execution will reach kategoribmi = "something". If the if statement where you assign a value to kategoribmi will not be true at execution, the variable will not be assigned. And whether this will be the case or not, cannot be known at compile time.

The simple solution to this is to assign a default value to kategoribmi before the first set of if statements, like so:

kategoribmi = ""

if kelas == "('15', 'P')":
    if bmi > 28.2:
        kategoribmi = "obese"
    elif bmi >= 23.6 < 28.2:
        kategoribmi = "overweight"
    elif bmi <= 15.8:
        kategoribmi = "underweight"
    else:
        kategoribmi = "ideal"

if kategoribmi == "underweight":
    underweight()
elif kategoribmi == "overweight":
    overweight()
elif kategoribmi == "obese":
    obese()
else:
    ideal()
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement