Data Validation & Error Handling

Data Validation & Error Handling

Validating user input

One of the most important aspects of programming is ensuring that your data is valid and error-free. Invalid data can lead to unexpected results and errors in your program. When you’re working with user-submitted data in your Python programs, there are many ways in which that data can go wrong. Users will often enter information in the wrong format, or leave out important details. Your program must be able to identify and handle these errors effectively if you’re going to produce reliable results from your code. Data validation and error handling are essential parts of any program that works with user input. We will take a look at how to scrub your data and handle errors effectively so that they do not cause problems downstream.

How to validate user input

There are two main ways to validate data:

  1. Data validation

    Data validation is the process of ensuring that your data is correct and error-free. This can be done by using a data validation library or by writing your own data validation code

  2. Error handling

    Error handling is the process of dealing with errors that occur during the execution of your program.

This article will explain both data validation and error handling in Python. We will also learn how to write our own data validation code.

Doing basic data validation using Loops.

Let's create a program that accepts the number of kills a gamer makes in call of duty for two game days. We will determine whether a gamer has progressed to the next stage or failed depending on average kills and mission completion rate

game_day1 = int(input("Enter the number of kills made in game day 1:"))
game_day2 = int(input("Enter the number of kills made in game day 2:"))
total_mission = int(input("Enter the total number of missions in game day 1&2 :"))
mission_failed = int(input("Enter the number of missions failed:"))
avg_kill = (game_day1 + game_day2) / 2
mission_completed = (total_mission - mission_failed) / total_mission
print("Average kill:", round(avg_kill, 2))
print("mission completion rate", str(round((mission_completed * 100), 2)) + "%")

if avg_kill >= 10 and mission_completed >= 0.8:
    print("Congratulations! you've progressed to the next stage")
elif avg_kill < 10 and mission_completed < 0.8:
    print("sorry! you fail to qualify due to average kill less than 10 and mission completion rate lower than 80%")
elif mission_completed >= 0.8:
    print("sorry! you have an average kill less than 10")
else:
    print("sorry! mission completion rate is lower than 80%, you fail!")

Now let's get the output of the program above

Enter the number of kills made in game day 1: 15
Enter the number of kills made in game day 2: 12
Enter the total number of missions in game day 1&2: 20
Enter the number of missions failed: 2
Average kill: 13.5
mission completion rate 90.0%
Congratulations! you've progressed to the next stage

Now our program is running efficiently but there are few problems that may arise.

Problems highlighted from the above program

  1. Even though the program accepts number of kills ranging from 0 to 20, when the user inputs 100 by accident, the program will still accept the input and run.

  2. When the user inputs a string, the program automatically crashes and this results in an error.

We don't want our program to result in an error or accept wrong inputs. As a result, we incorporate data validation and error handling in our program.

User input validation procedure

  • Before asking for user input, create a variable, in this case data_valid and set it to False .

  • Start while loop and set data_valid == False.

  • Go inside the while loop and request for user input.

  • Now make your validation using conditional statements (if, elif and else).

After stating out the procedure to validate user input, let's begin validating the program we created earlier.

data_valid = False
while data_valid == False:
    game_day1 = int(input("Enter the number of kills made in game day 1:"))
    if game_day1 < 0 or game_day1 > 20:
        print("oops! number of kills ranges from 0 to 20")
        continue
    else:
        data_valid = True

As illustrated above, we've validated user input for game day 1. We will go ahead to validate the remaining user inputs to prevent our programming from accepting wrong inputs following the stated procedure.

data_valid = False
while data_valid == False:
    game_day1 = int(input("Enter the number of kills made in game day 1:"))
    if game_day1 < 0 or game_day1 > 20:
        print("oops! number of kills ranges from 0 to 20")
        continue
    else:
        data_valid = True

data_valid = False
while data_valid == False:
    game_day2 = int(input("Enter the number of kills made in game day 2:"))
    if game_day2 < 0 or game_day2 > 20:
        print("oops! number of kills ranges from 0 to 20")
        continue
    else:
        data_valid = True

data_valid = False
while data_valid == False:
    total_mission = int(input("Enter the total number of missions in game day 1&2 :"))
    if total_mission <= 0:
        print("The number of missions can't be zero or less")
    else:
        data_valid = True

data_valid = False
while data_valid == False:
    mission_failed = int(input("Enter the number of missions failed:"))
    if mission_failed < 0 or mission_failed > total_mission:
        print("The number of mission failed can't be less than 0 or greater than the number of total missions")
    else:
        data_valid = True

avg_kill = (game_day1 + game_day2) / 2
mission_completed = (total_mission - mission_failed) / total_mission
print("Average kill:", round(avg_kill, 2))
print("mission completion rate", str(round((mission_completed * 100), 2)) + "%")

if avg_kill >= 10 and mission_completed >= 0.8:
    print("Congratulations! you've progressed to the next stage")
elif avg_kill < 10 and mission_completed < 0.8:
    print("sorry! you fail to qualify due to average kill less than 10 and mission completion rate lower than 80%")
elif mission_completed >= 0.8:
    print("sorry! you have an average kill less than 10")
else:
    print("sorry! mission completion rate is lower than 80%, you fail!")

Let's check if our data validation is working for the various user inputs.

Enter the number of kills made in game day 1: 45
oops! number of kills ranges from 0 to 20
Enter the number of kills made in game day 1: 15
Enter the number of kills made in game day 2: 25
oops! number of kills ranges from 0 to 20
Enter the number of kills made in game day 2: 15
Enter the total number of missions in game day 1&2: -3
The number of missions can't be zero or less
Enter the total number of missions in game day 1&2: 0
The number of missions can't be zero or less
Enter the total number of missions in game day 1&2: 20
Enter the number of missions failed: -2
The number of mission failed can't be less than 0 or greater than the number of total missions
Enter the number of missions failed: 25
The number of mission failed can't be less than 0 or greater than the number of total missions
Enter the number of missions failed: 5
Average kill: 15.0
mission completion rate: 75.0%
sorry! mission completion rate is lower than 80%, you fail!

Process finished with exit code 0

Awesome! Our data validation worked perfectly well. The program is able to take care of wrong inputs but there might be a bit of a problem. When the user mistakenly enters a string, the program will automatically result in an error.

error.png

To take care of such problem, we do error handling.

Error handling procedure

When working with user input, always make sure that not only the data is valid and also within range but also make sure that a bad input will not cause the program to crash. In order to achieve such satisfaction, we employ the try and except block.

  • First call out for user input without making conversion to desired data type.

  • Open the try block and make the conversion. This works in the same way as conditional statements and loops.

  • Open the except block. Now comes the best part. Instead of the program crashing after an error, the program jumps to the except block where the error can be handled. An illustrative example of error handling is shown below.

number = input("Type a number:")
try:
    number = float(number)
    print("The number is",number)
except:
    print("Invalid input")

Output

Type a number: test
Invalid input

It can be clearly seen that instead of the program crashing after inputting a string, the error was handled. We can then go on to follow this procedure to prevent the program from crashing.

data_valid = False
while data_valid == False:
    game_day1 = input("Enter the number of kills made in game day 1:")
    try:
        game_day1 = int(game_day1)
    except:
        print("Invalid input,only numbers are accepted")
        continue

    if game_day1 < 0 or game_day1 > 20:
        print("oops! number of kills ranges from 0 to 20")
        continue
    else:
        data_valid = True
data_valid = False
while data_valid == False:
    game_day2 = input("Enter the number of kills made in game day 2:")
    try:
        game_day2 = int(game_day2)
    except:
        print("Invalid input,only numbers are accepted")
        continue
    if game_day2 < 0 or game_day2 > 20:
        print("oops! number of kills ranges from 0 to 20")
        continue
    else:
        data_valid = True
data_valid = False
while data_valid == False:
    total_mission = input("Enter the total number of missions in game day 1&2 :")
    try:
        total_mission = int(total_mission)
    except:
        print("Invalid input,only numbers are accepted")
        continue
    if total_mission <= 0:
        print("The number of missions can't be zero or less")
    else:
        data_valid = True
data_valid = False
while data_valid == False:
    mission_failed = input("Enter the number of missions failed:")
    try:
        mission_failed = int(mission_failed)
    except:
        print("Invalid input,only numbers are accepted")
        continue
    if mission_failed < 0 or mission_failed > total_mission:
        print("The number of mission failed can't be less than 0 or greater than the number of total missions")
    else:
        data_valid = True


avg_kill = (game_day1 + game_day2) / 2
mission_completed = (total_mission - mission_failed) / total_mission
print("Average kill:", round(avg_kill, 2))
print("mission completion rate", str(round((mission_completed * 100), 2)) + "%")

if avg_kill >= 10 and mission_completed >= 0.8:
    print("Congratulations! you've progressed to the next stage")
elif avg_kill < 10 and mission_completed < 0.8:
    print("sorry! you fail to qualify due to average kill less than 10 and mission completion rate lower than 80%")
elif mission_completed >= 0.8:
    print("sorry! you have an average kill less than 10")
else:
    print("sorry! mission completion rate is lower than 80%, you fail!")

Inputting strings as user inputs to see if our error handling process is working

Enter the number of kills made in game day 1: test
Invalid input,only numbers are accepted
Enter the number of kills made in game day 1: 12
Enter the number of kills made in game day 2: Ten
Invalid input,only numbers are accepted
Enter the number of kills made in game day 2:12
Enter the total number of missions in game day 1&2 : test
Invalid input,only numbers are accepted
Enter the total number of missions in game day 1&2 : 20
Enter the number of missions failed: None
Invalid input,only numbers are accepted
Enter the number of missions failed: 2
Average kill: 12.0
mission completion rate 90.0%
Congratulations! you've progressed to the next stage

Process finished with exit code 0

Congratulations! error handling and data validation are working perfectly well. The program is able to take care of wrong inputs without crashing.

Conlusion

Every programming language has its own data validation and error handling practices. This is a topic that we find to be incredibly frustrating in many programming languages. Learn how to use them in Python by reading this article! Many people who are new to programming feel overwhelmed by the idea of error handling and data validation. We went through some helpful tips that will help you understand what data validation and error handling are and how to implement them in your programs. Copy the above codes into your code editor to practice . Thank you for reading!