Validating Types and Data in Python

udanielnogueira

Daniel Nogueira

Posted on November 5, 2022

Validating Types and Data in Python

We can find out the type of a variable using the type() function, that allows us to check what type of variable the algorithm will accept or not.

Let's read a variable that's not being converted to an integer, so it's a string:

x = input('Type something: ')
Enter fullscreen mode Exit fullscreen mode

Then we run the type() function inside the print() function, to display the type of the variable x on the screen:

print(type(x))
Enter fullscreen mode Exit fullscreen mode

The result will be:

<class 'str'>
Enter fullscreen mode Exit fullscreen mode

Basic validation

Here is a brief validation of the variable, if it's not int, the code will execute the programmed condition:

if type(x) != int:
    print('The variable is not integer')
Enter fullscreen mode Exit fullscreen mode

Advanced validation

We can get so much more informations from a variable in the program, just run some of the methods:

#Contains only letters?
isalpha()

#Contains only spaces?
isspace()

#Contains only numbers?
isnumeric()

#Contains only uppercase?
isupper()

#Contains only lowercase?
lower()

#Contains only letters and numbers?
isalnum()

#First capital and others lowercase?
istitle()
Enter fullscreen mode Exit fullscreen mode

The result returned will be True or False.

Let's run the methods with a y variable:

print('Only letters?', y.isalpha())

print('Only spaces?', y.isspace())

print('Only numbers?', y.isnumeric())

print('Upper case only?', y.isupper())

print('Lower case only?', y.islower())

print('Is it capitalized?', y.istitle())

print('Letters and numbers only', y.isalnum())
Enter fullscreen mode Exit fullscreen mode

Try entering different inputs until you fully understand the concepts of each method.

In practice

We can, for example, use the isnumeric() method to validate a Zip Code. In which the program will proceed when the user enters only numbers.

Or use the istitle() method to check the Name field of a form. If the name entered is not capitalized, we can validate and even make the necessary changes to the variable.

💖 💪 🙅 🚩
udanielnogueira
Daniel Nogueira

Posted on November 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related