Convert letter grade
Assume the input is a finite number; decimals within the stated bands are allowed.
Write a Python function that takes a numeric grade (0 to 100) as input and returns the corresponding letter grade (A, B, C, D, or F) using if/elif/else statements.
The grading scale is as follows:
- if
90 <= grade <= 100, return “A”. - if
80 <= grade < 90, return “B”. - if
70 <= grade < 80, return “C”. - if
60 <= grade < 70, return “D”. - if
0 <= grade < 60, return “F”.
If the grade is outside the range 0 to 100, return “Invalid Grade”.
Complete Listing 1. Save the completed code as convert_to_letter_grade.py and run it to check the supplied assertions.
def convert_to_letter_grade(grade: float) -> str:
raise NotImplementedError("Replace this line with your code.")
# Inside a band
got = convert_to_letter_grade(78)
assert got == "C", f"78: expected 'C', got {got!r}"
# At the bottom of the A band
got = convert_to_letter_grade(90)
assert got == "A", f"90: expected 'A', got {got!r}"
# Just below it
got = convert_to_letter_grade(89)
assert got == "B", f"89: expected 'B', got {got!r}"
# At the bottom of the D band, and just below it
got = convert_to_letter_grade(60)
assert got == "D", f"60: expected 'D', got {got!r}"
got = convert_to_letter_grade(59)
assert got == "F", f"59: expected 'F', got {got!r}"
# Both ends of the valid range
got = convert_to_letter_grade(0)
assert got == "F", f"0: expected 'F', got {got!r}"
got = convert_to_letter_grade(100)
assert got == "A", f"100: expected 'A', got {got!r}"
# Outside the valid range, on each side
got = convert_to_letter_grade(105)
assert got == "Invalid Grade", f"105: expected 'Invalid Grade', got {got!r}"
got = convert_to_letter_grade(-1)
assert got == "Invalid Grade", f"-1: expected 'Invalid Grade', got {got!r}"
# Your case: which grade is most likely to break it?
# got = convert_to_letter_grade(___)
# assert got == "___", f"___: expected '___', got {got!r}"
TipHint
assert conditionchecks a Boolean condition. A true condition produces no output; a false condition raisesAssertionError. For example,assert 2 + 3 == 5passes.