Input Validation and Error Handling with Python
Validate your inputs and negate errors with these short but very useful blocks of Python code
Getting user inputs is one of the most crucial part of any program. What’s more important is to get the right type of input so that the program continues to run without problem.
Just like any other programming language, you can easily write a block of code to validate and filter a user input to ensure the program takes the only correct type of input with Python. You can even create a loop that keeps sending a message to inform the user to input correctly before going to the next step.
For example, assuming that you need to create a program which takes an integer from the user to perform further operations, you’ll write the following block of code to transform any whole number input into an integer:
#Getting an integer as an input
num = int(input("Please enter an integer :"))
Try an input any whole number with the above code and there’s no problem. The variable num stored any whole number you typed in as an integer. Great! The first layer of input validation is successfully pealed. Did I say layer? Yes. That’s because there can be many layers stacked on top of an input validation process, depending solely on what is needed for it to perform.
The code above will work fine as long as the user inptut a whole number. It breaks easily, however, when it gets something that is not a whole number such as ‘3.14’ or ‘pi’. In other words, the code above will throw an error message if the user give it anything but a whole number:
#Getting an integer as an input
num = int(input("Please enter an integer :"))
#Give '3.14' or 'pi' as an input:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
----> 1 num = int(input("Please enter an integer: "))
ValueError: invalid literal for int() with base 10: '3.14'
We can easily avoid the above error by using try and except as shown in the following code block to catch the error:
try:
num = int(input("Please enter an integer: "))
except ValueError:
print("Please input a valid integer.")
As we already know, without the try except block, the code will throw a ValueError error if the input is anything that can’t be converted into an integer by the int() function, so we specifically tell the try except block to catch this type of error in the code above. However, the program just ends and we need to restart the program again if we are to give it another input.
A while loop can ease this pain. We can create a loop that will never stop telling the user to give the correct type of input until he/she does so:
while True:
try:
num = int(input("Please enter an integer: "))
break
except ValueError:
print("Please input a valid integer.")
Basically, the above code tells the program to keep asking the user for a valid integer until it gets one. Once the input is correct, the loop is terminated with the break command. However, it will keep telling the user “Please input a valid integer.” until it gets one. This way, we don’t have to restart the program every time we give it a wrong input. And there’s no error message. The program keeps running (validating the input) smoothly even when we give wrong types of inputs. The second layer of the input validation process is cracked!
In general, the more specific an input, the more smoothly the program (or data processing) in the later phases will perform. Let’s say, for example, that we need to validate the input so that it’s an integer with the value ranges from 1 to 10 only, we can tweak the above code so that it will take only the said values like the following:
while True:
try:
num = int(input("Please enter an integer: "))
if num > 10 or num < 1:
print("Please input a valid integer.")
else:
break
except ValueError:
print("Please input a valid integer.")
Simply adding an if block that will tell the user to input a valid integer anytime when the value of the variable num is out of the 1–10 range does the trick of letting the program be even more specific about ingesting any input from the user based on the condition(s) in the if block.
The third layer is cracked!
You can also apply this knowledge in validating inputs of string type without having to down-cast it to any other data type as well, since the initial data type of the input() function is already string.
print(type(input("Please give any input: ")))
#Input "hello"
<class 'str'> #Output shows the data type of the input() function as 'str'
Let’s say that, for some reason, you need a program to input a string with only 3 characters in length, you can write a block of code to validate the input according to the said condition like so:
while True:
str_input = input("Please input a string: ")
if len(str_input) == 3:
break
else:
print("Please input a valid string.")
The above code will keep asking the user for any input with specifically 3 characters in length. Anything less or more than 3-character long will be disregarded.
There you have it, some easy tricks to validate inputs and negate errors with Python.
In summary, there are basically 3 main layers for input validation:
- Type-cast the input as needed just as the example of casting a string to an integer with the int() function.
- Use the while loop to negate error, let the process of data validation runs smoothly until the program gets the correct type of input.
- Create conditions so that the input is more tailored to what the user reallly needed. This layer is very important for the future data processing and operations. It minimalizes the chances of future possible errors!
Bonus:
You see how we can specifically handle the ValueError with the try except block. What if we don’t know what type of error will happen and we just want to handle an error? We can do so with the following code:
#Catch a generic error:
while True:
try:
num = int(input("Please enter an integer: "))
break
except Exception:
print("Please input a valid integer.")
In the code above, we can use Exception to handle a variety of types of unexpected (or unknown) errors.
I do hope you find this short article about input validation with Python useful an applicable with your works. Enjoy coding. Until next time!