Why the value of the variable 'grade' is "F"?

https://www.codecademy.com/courses/learn-python-3/lessons/python-control-flow/exercises/else-if-statements

Hello there~

Regarding this exercise:

Calvin Coolidge’s Cool College has noticed that students prefer to get letter grades over GPA numbers. They want you to write a function called grade_converter that converts an inputted GPA into the appropriate letter grade. Your function should be named grade_converter , take the input gpa , and convert the following GPAs:

  • 4.0 or higher should return "A"
  • 3.0 or higher should return "B"
  • 2.0 or higher should return "C"
  • 1.0 or higher should return "D"
  • 0.0 or higher should return "F"

You can do this by creating a variable called grade .

Then, you should use elif statements to set grade to the appropriate letter grade for the gpa entered.

At the end of the function, return grade.

The answer is:

def grade_converter(gpa):
  grade = "F"

  if gpa >= 4.0:
    grade = "A"
  elif gpa >= 3.0:
    grade = "B"
  elif gpa >= 2.0:
    grade = "C"
  elif gpa >= 1.0:
    grade = "D"

  return grade

In this exercise, why the value of the variable grade is F?

Would it be possible to add other grades instead of F?

Also, why wasn't the last elif replaced to else? I thought 
the last statement should be else(if--elif--else).

And, what would happen if I write like this?

 
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"


Thank you for your assistance in advance.

Hi @object1209001660,
In this exercise, why the value of the variable grade is F?
I guess it is system that passes the argument to your function and it evaluates to “F” but it can be anything.

Regarding the two approaches - #1 & #2.

#1 - You are pre-setting the value of grade - By doing this, You don’t need “else” case. [else is optional block so you can skip it.] As if no condition meets It will be “F”. This solution works for all real numbers [-ve numbers included]

And, what would happen if I write like this?

#2 - This solution looks the same but with slight difference, It does not consider -ve numbes.

Would it be possible to add other grades instead of F?
Yes, It can be extended depending upon range.

Hope it helps,let me know if you have more queries.

2 Likes

Thank you so much! :slight_smile: