Every time a user submits an input, it must be validated to see if it is exactly what we expected. We can validate the input in one of two ways: by applying a flag variable or implementing try or except. The flag variable will be originally set to false, and if we determine that the given data is the same as our expectation, we will change the flag status to true. From there, we can determine what we can do next, depending on the flag status. If the result is unfavorable, the except code block is executed.
Types of Validation in Python
Broadly we can categorize the validation problems into these three categories:
Type Check: The supplied data type is verified using one of the Python validation methods. The Python data types are such as int, float, etc.
Length Check: The length of the provided input string or any iterable is verified using any of the described Python validation methods.
Range Check: Python's validation method can also be implemented to determine whether the supplied input number falls between the two specified numbers.
Below we have described the Syntax of validation methods:
Syntax using the flag:
The flag's status is originally set to false, and the exact condition is considered during a while loop to keep the statement from becoming true. If the required validation condition is fulfilled, the flag is validated and set to true; if not, an error message is produced.
We first set the condition of the while loop to be true and, after that, run a code block to perform the required validation. If the code cannot complete the verification, an exception will be raised that displays the error message. A success text is printed if the try code block successfully completes the code.
Examples of Python Validation
Examples show the implementation of the validation methods described above.
We will check whether the input has the required data type.
Please type a number: 8.8 The input given is not a valid integer The given input is an integer and that is: 8.8
The Python program validates the user-provided input using a flag variable to see if it falls inside a certain range.
Please type a number: 7 The number given by you does not lie between 13 and 19 The number given by the user lies between 13 and 19 and the number given by you is: 7
The Python program uses the flag variable to determine the input of the string's length.
Please give a string: Python The given input string has a length greater than or equal to 5, and the string is: Python
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week