Concepts / Error Handling with try and except

Error Handling with try and except

The computegrade function takes a score as a parameter and returns a letter grade as a string, using if and elif conditions to check thresholds from highest (A: >= 0.9) to lowest (F: < 0.6).

  • Programming

From Grade Program to Reusable Function

A grade program becomes easier to reuse and debug when its logic is placed inside a function named computegrade. The function accepts one score and returns a letter grade as a string. Because the grading logic has one focused location, you can call it repeatedly and investigate incorrect results without rewriting the entire program.

The computegrade function converts a numerical score into a letter grade by checking score thresholds from the highest threshold to the lowest. It returns the first grade whose condition is true.

receivednumeric inputconversion failsscorefunction inputfloat conversiontryletter gradeA, B, C, D, or FA Bad scoreexcept result
How does a score move through the function and become either a letter grade or an error message?

Thresholds and Branch Order

The grading scale treats a score as a decimal between 0 and 1, with 1.0 representing 100 percent. Each threshold is inclusive: a score exactly equal to a threshold receives that grade. The conditions therefore need to be checked from highest to lowest: A at 0.9 or higher, B at 0.8 or higher, C at 0.7 or higher, D at 0.6 or higher, and F below 0.6.

python

The order matters because an if and elif chain stops at the first true condition. For example, a score of 0.85 does not satisfy the A condition, but it does satisfy the B condition. Once the B branch is reached and found true, the remaining branches are not checked.

checkfalsefalsetrue0.75scoreA threshold0.9 or higherB threshold0.8 or higherC threshold0.7 or higherCfirst true condition
Which threshold is checked first, which branch is taken, and why does the function stop there?

Tracing a Score of 0.75

Following the First True Branch

Determine the result of computegrade(0.75).

Check A: The score is 0.75, which is below 0.9, so the A condition is false.

Check B: The score is below 0.8, so the B condition is false.

Check C: The score is at least 0.7, so the C condition is true.

Stop: Because the C branch is the first true condition, the function returns C and does not check the lower branches.

computegrade(0.75) returns C.

Output
C

Tracing is useful when the result differs from what you expected. Write down the input, inspect each condition in order, and stop at the first condition that evaluates to true. If a function gives an unexpected grade, this process can reveal whether a threshold was written incorrectly or whether the conditions were placed in the wrong order.

Catching Invalid Scores

A user may provide a non-numeric value such as the word perfect instead of a number. The function should handle that situation gracefully rather than allowing the conversion attempt to stop the program. A try-except block lets the function attempt to convert the input to a float. If that conversion fails, the except block returns the message A Bad score.

python

The function has two possible successful paths after the try statement. A numeric input continues to the grade conditions. A non-numeric input moves directly to the except branch and returns A Bad score. In that second path, the threshold checks are never reached because there is no usable numeric score to compare.

beginnumericmatching branchnon-numericinput scorefunction callfloat conversiontrygrade thresholdsif and elifletter gradereturned resultA Bad scoreexcept result
What happens next when computegrade receives a numeric score versus an invalid input?

Boundary Values and Test Coverage

A reliable test set should include ordinary scores, exact threshold values, scores just below thresholds, and invalid inputs. Boundary tests are especially important because the thresholds are inclusive. Testing 0.9 verifies the A boundary, while testing a value just below 0.9 verifies that the score moves to the next lower category.

InputExpected resultWhy test it
0.95AValid score in the A range
0.90AExact A threshold
0.85BValid score in the B range
0.80BExact B threshold
0.75CValid score in the C range
0.70CExact C threshold
0.65DValid score in the D range
0.60DExact D threshold
0.59FBelow the D threshold
perfectA Bad scoreNon-numeric input

Representative tests for the computegrade function

cross 0.9cross 0.8cross 0.7cross 0.60.89B0.79C0.69D0.59F0.90A0.80B0.70C0.60D
How do exact threshold values compare with values just below the threshold?

Mistakes Beginners Make

  • Checking thresholds from lowest to highest

    A broad lower-threshold condition can become true before the function reaches the more specific higher grades.

    Fix: Check A, then B, then C, then D, and finally F.

  • Treating an exact threshold as belonging to the lower grade

    Thresholds are inclusive, so a score exactly equal to 0.9 receives A.

    Fix: Use comparisons that include the threshold, such as score >= 0.9.

  • Allowing a non-numeric input to reach the comparisons

    The input must first be converted to a float, and a failed conversion needs to be handled.

    Fix: Place the conversion in a try block and return A Bad score from the except block.

  • Testing only one ordinary score

    A single successful case does not verify boundaries, all grade ranges, or invalid input behavior.

    Fix: Test representative values, exact thresholds, values below thresholds, and non-numeric input.

Practice the Execution Path

MEDIUM

For each input, predict the returned string before tracing the conditions: 0.95, 0.80, 0.69, and perfect. Then identify the first condition that is true, or identify where the try-except path handles the input.

Hints
  • Start with the A threshold and move downward.
  • Remember that exact thresholds are included in their grade.
  • A non-numeric input does not continue to the grade comparisons.

What do you think happens?

What does computegrade(0.80) return?

  • A
  • B
  • C
  • A Bad score
Reveal answer

Answer: B

The score is below 0.9 but exactly equal to the inclusive 0.8 threshold, so the B condition is the first true condition.

Reliable Grade Functions

  1. computegrade accepts a score and returns a letter grade as a string.
  2. Check thresholds from highest to lowest because the function stops at the first true if or elif condition.
  3. The thresholds are inclusive: 0.9, 0.8, 0.7, and 0.6 receive A, B, C, and D respectively.
  4. Use try-except around the float conversion so non-numeric input returns A Bad score.
  5. Test ordinary values, exact boundaries, values below boundaries, and invalid input to verify the function.

Key Takeaways

  • A reusable computegrade function centralizes score-to-grade logic.
  • An if and elif cascade must test grade thresholds from highest to lowest.
  • try-except handles non-numeric input by returning A Bad score.
  • Execution tracing reveals which condition first determines the result.
  • Systematic tests verify grade ranges, inclusive boundaries, and invalid inputs.