How to know the primitive type of a variable in python

Asked

Viewed 379 times

-3

(I am inciante)

I have the following dictionary:

'''
d = {'nome': ' ', 'Idade': 0, 'carteira de trabalho': 0,
 'ano de contrato': 0, 'salário': 0.0}
'''

This is the initial version of it, and I have to enter new values as the user type them. I thought I’d use a loop for to do this.

'''
for k in d.keys():
    d[k] = input(f'{k}: ')
'''

The problem is: Some values in the dictionary are strings, while others are ints. I thought about solving the problem using an if, but for that I will need to know what is the primitive type of the value k.

1 answer

1

Samuel,

To return the variable type, you can use the function type from Python, it returns what type of variable.

There is also the function isinstance, that instead of returning a type, you send the type and variable and it returns a Boolean as the variable is of the type you entered.


Take an example:

inteiro = 0
string = "string"

print(type(inteiro))
print(type(string))

if type(inteiro) == int:
  print("É um inteiro")

if type(string) == str:
  print("É uma string")

print("É uma string?", isinstance(string, str))
print("É um inteiro?", isinstance(inteiro, int))

See online: https://repl.it/repls/GargantuanBrokenNature


Reference:

https://docs.python.org/3/library/functions.html#type

https://docs.python.org/3/library/functions.html#isinstance

Browser other questions tagged

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