Which return of a function is better?

Hi there, this is my first-week programming and I got a question about two samples of code I want to share with you. I want to know which one is better and why?
The difference is in the return of the function.

# def. func. letter grades over GPA
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

#calling the func.
gpa = 3.0
letter_grade = grade_converter(gpa)

#printing the func.
print(letter_grade)

or

# def. func. letter grades over GPA
def grade_converter (gpa):
  if (gpa >= 4.0):
    return "A"
  elif (gpa >= 3.0):
    return "B"
  elif (gpa >= 2.0):
    return "C"
  elif (gpa >= 1.0):
    return "D"
  elif (gpa >= 0.0):
    return "F"

#calling the func.
gpa = 2.0
letter_grade = grade_converter(gpa)

#printing the func.
print(letter_grade)

Thanks.

I would think the second one is better due to the fact that it won’t have to run the return grade line of code.

As such I believe it would make the code run ever so slightly faster, though on a program this small that shouldn’t make much of a difference.
It also would not have to go to the trouble of creating the variable grade that is not needed, since it will be deleted as soon as the function ends.

However if you wanted to do more to the grade variable, than the first option would might be better for you.

1 Like

I actually implemented the second one, the first one was suggested by code academy and that’s what prompted me to ask and check which of the two was better. I totally share the same view you just mentioned.

1 Like

While both are acceptable (I won’t say which I prefer.), using else for the last option would be preferable in general: if - elif - else. Presumably, the teaching point is to emphasize the if - elif - else syntax.

1 Like