This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 10: Input validation

Code robustness

face Josiah Wang

So far, we assume that any inputs are valid. These include inputs that are entered by a user or provided as argument of a function call.

We cannot, however, always assume that the input will always be valid in the real world. You might get some input that may cause an error. It might be an invalid value, or it could even be an invalid type, or worse you might even get a None object!

For example, the function below should work fine in most cases, unless the value of denominator is 0. In that case, Python will raise a ZeroDivisionError and exit the program.

1
2
3
def calculate(numerator, denominator):
    result = 2 * (numerator+3) / denominator
    return result

So, other than making sure that your program behaves correctly with valid inputs, you should also make sure that it is stable and robust enough so that it does not crash the moment it meets an invalid input.

In this chapter, we will explore two different approaches to dealing with invalid input.

This chapter is important for your courseworks as the automated tests will check your code thoroughly to make sure it responds correctly to both valid AND invalid inputs!