how to check specific type of variable | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

how to check specific type of variable

i've tried : x = 3 if x == int: print("it is interger") else: print('it is not interger") it give me an error. is there any method to do this ?

28th Jul 2016, 5:02 AM
Erlangga Ibrahim
Erlangga Ibrahim - avatar
8 Answers
+ 6
x = 5 if type(x) == int: print("integer") else: print("not an integer") you missed the type() function
28th Jul 2016, 6:39 AM
sundar
sundar - avatar
0
to check the type you can use isinstance function. your x == int can be replaced with isinstance(x,int) in the similar way you can check other types (float, str or classes)
28th Jul 2016, 6:37 AM
RedAnt
RedAnt - avatar
0
@francisco you got the point its not the problem
28th Jul 2016, 6:42 AM
Erlangga Ibrahim
Erlangga Ibrahim - avatar
0
@sundar thanks a lot man !
28th Jul 2016, 6:43 AM
Erlangga Ibrahim
Erlangga Ibrahim - avatar
0
just type in type <>
30th Jul 2016, 5:14 AM
Narek Tonoyan
Narek Tonoyan - avatar
- 1
The second print() begins with a single quote and ends a double quotes. There is your problem. 😋
28th Jul 2016, 5:59 AM
Francisco Gómez García
Francisco Gómez García - avatar
- 1
@Francisco Gomez. you found syntax error, I found semantic error :-) even he change it to double quotes he need to check the type by comparing so. the condition always be else block, even it's an integer.
28th Jul 2016, 6:43 AM
sundar
sundar - avatar
- 1
@RedAnt. Thanks man I didn't know it.
28th Jul 2016, 6:49 AM
sundar
sundar - avatar