Hello again everybody, I am sorry that I have not posted in the last couple of weeks. It’s December now, and Christmas time is approaching. In the meantime, here is a new Python tutorial about validation.
What is validation? It’s a way of checking whether something is a certain value or not, and executing code depending on the result. Code uses validation all the time. If you are signing up for an email address, it may ask you for your phone number, for example. If you type in an invalid phone number (for example, if you put a letter in the number) then it will refuse to continue until you’ve corrected this mistake.
For this tutorial, I will be using a very basic example. The program will ask the user to enter in a lowercase letter. Once the user has done so, the program will check if the character is in a list of specified lowercase letters. If it is, the program will say that the input is valid, and exit. If it isn’t, the program will declare the input not valid, and ask the user to try again.
Here is the code:
validchars = "abcdefghijklmnopqrstuvwxyz"
valid = False
while valid == False:
letter = input("Enter a lowercase letter: ")
if letter in validchars:
print("That is a valid character.")
valid = True
print("Sorry, that's invalid.")
Let’s take a look at the code. The first line creates a variable called validchars, consisting of all the valid characters that can be used. The second line creates a boolean variable called valid, and sets it to False.
The third line, while valid == False: declares that as long as valid is equal to False, the following code will run. The next line asks for the user to type in a lowercase character and stores it in variable letter.
The fifth line, if letter in validchars:, checks if the user-inputted letter variable is in the string validchars. The next two lines of code will be executed if this is the case. The next lines print out telling the user it is valid, and then set valid to True. If this code is executed, the program will end as the while loop will no longer work with valid as something other than False.
The final lines will be executed if letter isn’t in validchars. It tells the user the character is invalid, and does not update valid to True. As a result, the program will repeat again until letter is found to be in validchars, and then the program will exit.
I hope this tutorial helped you in some way. This is only the basics, and there are many more things you can do with validation that I may cover in a future tutorial. Goodbye! 🙂