To do this check, you can use the function type passing its variable as argument ID
. What this function does is simply return the class to which the object belongs. So you can check whether or not it is an integer that way:
if type(ID) == int:
print("É um número inteiro.")
else:
print("O valor de ID é um",type(ID))
The problem is that as you are using the method get
of Entry objects, you will always get a string regardless of whether the input is a number or not.
Then use the string method isnumeric
to know if it is a number or not. Example:
if ID.isnumeric():
print("É um número inteiro.")
else:
print("Não é um número inteiro.")
It is important to warn that this method is very comprehensive and there are several characters defined by Unicode which are considered numbers for the method isnumeric
.
Clicking here to see the list of characters the method returns True
.
Using a Try-except block:
You can also check whether the value obtained is a number or not by making a conversion of the value to int()
within a block Try - except.
If the value is converted correctly, it means that it is numerical and the program will continue in the block try
. If it is not possible to convert it, the ValueError
generated will make the program enter the block except
. See the example below:
try:
ID = int(ID)
print("ID é um número inteiro.")
except:
print("ID não é um número inteiro.")
Using isinstance and issubclass:
Running away now a little bit from the question of whether the data is numerical or not, we can check types of objects in a better way, which is using the functions isinstance and issubclass.
What the function isinstance
returns True or False by checking if an object is an instance of an X class.
isinstance( "Olá mundo!", str ) # True
isinstance( 2.345, int) # False
Already the function issubclass
returns True or False by checking if a class Y is a child of class X, that is, we check if class Y is sub-class x.
class ClasseX: pass
class ClasseY ( ClasseX ): pass
issubclass( ClasseY, ClasseX ) # True
issubclass( ClasseY, object ) # True
issubclass( int, object ) # True
issubclass( str, float) # False
Observing: Unlike the functions type
and isinstance
, should not be passed as a parameter to the function issubclass
an object and yes a class. So if we wanted to check if an object belongs to a daughter class of X, we must first get its class, example:
classe = type(objeto)
print( issubclass( classe, ClasseX ) )
People what I did wrong in the formulation? Here is not to ask this no?
– Jhonatas Flor de Sousa
You can’t understand what you want.
– danilo
Ah right I’ll fix it, thank you Danilo
– Jhonatas Flor de Sousa