Define type of variable in a function

4

Good, I am learning Python and I was curious, since I am new in this programming, when declaring a variable in a function, can not you specify the type of variable as if you did it normally? I want to do this but you can see that the program does not leave me.

def es_par(int(numero)):
if numero%2==0:
    return True
else:
    return False
print(es_par(input("Introduce un numero")))

The only solution I find is to do this:

def es_par(numero):
if numero%2==0:
    return True
else:
    return False
print(es_par(int(input("Introduce un numero"))))

Thank you very much and sorry for my ignorance:)

    
asked by David Hidalgo Muñoz 12.12.2017 в 11:22
source

2 answers

1

In Python the data types are calculated on the fly (dynamic). What you can do is check if it is an integer and if not, generate an exception of the wrong type.

    def esPar(n):
       if not isinstance(n, (int, long)):
           raise TypeError('no es un entero')
       return n % 2 == 0
    
answered by 12.12.2017 / 11:49
source
4

It is possible to indicate the type with type annotations ( "gradual typing" ):

def es_par(numero: int) -> bool:
    return numero%2 == 0

But it is only an indication, it does not prevent errors if you pass arguments of another type. In python there is no "static typing" .

    
answered by 12.12.2017 в 20:43