Why don't I get a NameError in this case?

I’m lack of a variable grade = "", but when I run the code - I get no error message nor printed answer in the console. Why is that?

def grade_converter(gpa):
  if gpa >= 4.0:
    grade = "A"
  elif gpa >= 3.0:
    grade = "B"
  elif gpa >= 2.0:
    grade = "C"
  elif gpa >= 1.0:
    grade = "D"
  else:
    grade = "F"
  return grade

print(grade_converter(0.0))

The else clause will run:

  else:
    grade = "F"

which will give the variable a value. If you had something like:

def grade_converter(gpa):
  if gpa >= 4.0:
    grade = "A"
  elif gpa >= 3.0:
    grade = "B"
  elif gpa >= 2.0:
    grade = "C"
  elif gpa >= 1.0:
    grade = "D"
  elif gpa >= 0.0:
    grade = "F"
  return grade

print(grade_converter(-1))

then you would get an error. Now none of your conditions is true, so the variable is accessed before its initialized.

1 Like

Thank you for a quick reply! Oh, it also was just a lag from my side that caused the problem not to print the else result.

1 Like

Just to be on the safe side (maybe for other people reading this). @i.maksymov way (using else) is the good solution. My code was merely to demonstrate how to trigger an error

1 Like

So, I don’t even need to add grade = "" within a function or globally in order for the code to work. Is that because the first portion of a function creates a variable grade and stores "A" inside it? Then, the following portions of the function just reassign that variable to other outputs?

No, in your code, grade will always get a value. One of your clauses will run and give your variable a value.

which clause (if, elif or else) will run depend on the value for gpa.

1 Like