Daniel Nogueira
Posted on November 5, 2022
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: ')
Then we run the type()
function inside the print()
function, to display the type of the variable x
on the screen:
print(type(x))
The result will be:
<class 'str'>
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')
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()
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())
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.
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
November 1, 2024
October 6, 2024