Input Errors and Exception and how they are handled in Python

Level: Beginner

Hello Everybody,

Let’s look at a very simple piece of code.

This is a function (divisionfunction(a,b)) that accepts two values from a user, divides  the first value by the second value and then prints out the results of the division.

We have a very specific requirement, we would like our users to key in any value as either an Integer(Whole numbers) or float(Numbers with a decimal point) literals. The two values must be greater than or equal to 0.0. To accommodate either of the two we request for the input as a float.

For this example, we will look at 2 ways in which we can receive faulty input and how to handle that.

Example 1

Our user keys in a value less that 0.0. In our case -1.5

Without any adjustments to the code, it will accept the value and the code will run, However, our requirement clearly states that the value must be 0.0 or more.

How then can we force the code to strictly accept this input?

The Assert Keyword

One way of ensuring that your users key in the expected values is by using the assert keyword.

The assert key word checks your input data against a defined check. In our case the value must equal to or greater than 0.0

If that evaluation returns True, then nothing happens.

If it returns False, then an AssertionError is raised and the code terminates. The idea is to force your users to key in values within the expected range.

Let’s redo our code and use the Assert keyword, then we can test with an input of -1.5 and see what we get.

Example 2

So, what happens when a user decides to key in text. ‘hello‘ instead of an integer or float

Text are string literals, below is the error received. This immediately terminates your code, reason ValueError

Handling the input errors.

TRY: EXCEPT Keywords.

The try except blocks essentially enable you to try something and if it fails and an error(Exception) is raised it allows you to define how this will be handled.

We will rewrite the code above and allow for handling of the above two errors and any other errors that could occur.

In the above edited snippet, we specify how either of the two errors will be handled, by specifying the message that will be displayed on the screen.

The third error below is a bonus, can you tell why the code fails? Hint: ZeroDivisionError

Note: The general except block, that is the block that does not specify the exact exception or error we are mitigating, must always be defined last as it is a catch all for any other errors that could occur.


There are many more exceptions defined in python. And knowing some of the and their   hierarchies will help you better handle errors in your code.
For more information on more of them https://docs.python.org/3/library/exceptions.html


Networks Engineering, Networks Infrastructure Security, Networks Automation

Leave a Reply

Your email address will not be published. Required fields are marked *