An initial example of Input Error Handling in Python

https://miro.medium.com/max/1024/0*A0jf9favABy7b2fe

Original Source Here

An initial example of Input Error Handling in Python

As I have progressed in my studies of Python programming, I have begun to study error handling, which is important to ensure the robustness of a script. One type of error is an input error, which is an error that the user makes when he is inputting data.

I have included the code for a short script I have recently written. The script below is a very small program that will be able to tell the user whether an entered number is odd or even.

The user is prompted to enter a number and this number is converted from a string to an integer.

If the number is divisible by 2 then a message is printed saying it is an even number, otherwise a message is printed saying it is an odd number is printer.

The thing that is wrong with the below code is the fact there are no failsafe mechanisms put in place to ensure that only the desired data is entered:-

The code below is an adaptation to add an input error catching mechanism.

The program has now become a while loop. As long as the variable num is ‘y’ then the loop will operate.

Error handling code has been added to the program: The user is asked to enter a number and if it is an integer, a message saying it is odd or even will be printed out depending on whether the number is an odd or even integer.

If something other than an integer is entered, such as a string, the program will flow down to the exception code and a message saying it is not a valid number will be entered.

In both the try and exception statements the user will be asked if he would like to know if another number is odd or even. If the user enters ‘y’ then the program will continue until he enters something other than ‘y’:-

The code for these two scripts can be found in their entirety in my personal GitHub account, the link being here:- Games/Practice_Python.ipynb at main · TracyRenee61/Games (github.com)

AI/ML

Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: