Trying to figure out how to positively identify the variable types.
w = {}
x = ""
y = 2
z = []
a = type(w)
b = type(x)
c = type(y)
d = type(z)
print(a)
print(b)
print(c)
print(d)
if a == 'dict': print ("Ok - its a dict")
elif a != 'dict': print ("Wrong - its not a dict")
if b == 'str': print ("Ok - its a string")
elif b != 'str': print ("Wrong - its not a string")
if c == 'int': print ("Ok - its an int")
elif c != 'int': print ("Wrong - its not an int")
if d == 'list': print ("Ok - okay, its a list")
elif d != 'list': print ("Wrong - its not a list")
Generates the following output:
<class 'dict'>
<class 'str'>
<class 'int'>
<class 'list'>
The type() command generates a "class" structure, which makes it hard to positively identify the variable type in question.
Is there a way to get to the variable in the each class?
CodePudding user response:
you need to address python data types correctly.
'dict'
is not a data type but a string, however, dict
is. It is a python data type and it belongs to <class 'dict'>
.
w = {}
z = []
a = type(w)
b = type(z)
if a == dict:
print ("Ok - its a dict")
else:
print('it is not')
if type(z) == list:
print('z is a list')
else:
print('z is not a list')
output:
Ok - its a dict
z is a list
CodePudding user response:
I think, (please correct me if I am wrong), we are supposed to answer the final form of the question, yes? So here is my corrected code:
w = {}
x = ""
y = 2
z = []
a = type(w)
b = type(x)
c = type(y)
d = type(z)
print(a)
print(b)
print(c)
print(d)
if a == dict: print ("Ok - its a dict")
elif a != dict: print ("Wrong - its not a dict")
if b == str: print ("Ok - its a string")
elif b != str: print ("Wrong - its not a string")
if c == int: print ("Ok - its an int")
elif c != int: print ("Wrong - its not an int")
if d == list: print ("Ok - okay, its a list")
elif d != list: print ("Wrong - its not a list")
Which generates the following output:
<class 'dict'>
<class 'str'>
<class 'int'>
<class 'list'>
Ok - its a dict
Ok - its a string
Ok - its an int
Ok - okay, its a list