How to use the if block with variable types in Python?

Asked

Viewed 1,797 times

3

I am creating a program in Python and need that necessarily the data of the ID field are integer numbers. Basically I want to enter the block if depending on the type of variable I get. Example:

ID = "joão"

# Se ID não for string, deverá ser executado o código abaixo:
print("ID não é uma string")

Code to get the data:

from tkinter import *

def cria_entradas():
    # Código para criar os objetos de Entry ...

def pega_dados():

    nome = nome_entry.get()
    id  = id_entry.get()
    tipo = tipo_entry.get()
    localizacao = localizacao_entry.get()
  • People what I did wrong in the formulation? Here is not to ask this no?

  • You can’t understand what you want.

  • Ah right I’ll fix it, thank you Danilo

1 answer

5


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 issubclassan 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 ) )
  • That’s right, man, thanks.

  • In Python, one should avoid type checking with type(obj) == classe - once this validation breaks with subclasses and virtual classes. The correct is to check with the call isinstance: if isinstance(ID, int): in the case of your first example.

  • Thanks for your remark @jsbueno, I had really forgotten that function. I already added it to the answer and added the use of the function issubclass to make the answer more complete.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.