How to Program Python to check type of variable? | float or int or string or class
In programming, you need to store value in a variable to use it in your program. In other words, the variable is a placeholder for the data.
And data can be of different types like numerical value, string, image, etc.
So before using any variable in Python, you have to declare the variable in your code.
Let’s use this tutorial to learn- how to declare a variable? How to check the data type of each variable in Python?
What is the dynamic data type in Python?
Python follows dynamic data types. This is one of the features of Python programming.
This means we don’t need to specify the datatype of the variable explicitly.
For example, here is Python code for declaring variables of a different type.
Variable declaration in Python:
var = 27
#var is integer variable
var = "computer"
#var is string variable
The data type of the variable is decided based on the type of value assigned to the variable.
Later, I will share two programming methods in Python to check the type of variable.
How to check the data type of the variable?
You can use the type()
inbuilt function.
Pass name of the variable name as input the method type(). It returns the data type of the variable.
For example:
var = 10
type(var) #<type 'int'>
var = 10.5
type(var) #<type 'float'>
var = "Computer"
type(var) #<type 'str'>
var = [34, 57, 37]
type(var) #<type 'list>
When you assign 10 to the variable, the variable becomes an integer type. Here, int and float are the numerical data types in Python.
Why is it important to know the data type of variable?
Every data type has its own significance. There are some supported functions for each data type.
Let’s say, we can not do arithmetic operations on string datatype. Concatenation of two objects is valid only for the string.
Sometimes, you may want to manipulate the data based on its data type. So the comparing data types in Python is essential.
For example:
I am performing ‘+’ operations on integers as well as on strings data types.
strIn1 = "20"
strIn2 = "35"
print('String output: ',strIn1 + strIn2)
val1 = 20
val2 = 35
print('Numeric output: ',val1+val2)
Output:
String output: 2035 Numeric output: 55
In the above program,
- When I perform ‘+’ operations on the strings, it concatenates two string.
- When I perform ‘+’ operations on the integers, it performs an arithmetic addition operation.
So the comparing data types in Python is essential before performing some operations.
Different methods in Python to check the type of variable
Method 1: Using isinstance() function:
The isinstance()
function takes two parameters as an input.
If the variable (first parameter) is an instance of data type (mentioned as the second parameter), this function returns true.
For example:
n =16
isinstance(n, int) #True
isinstance(n, long) #False
isinstance(n, str) #False
Here you can also pass the Python tuple as the second argument. Below code checks, if the variable ‘n’ belongs to any of the str, int or float data type.
n =17
isinstance(n, (str, int, float) #True
Here is a simple program that takes input from the user and saves in variable var. Based on the data entered by the user, the data type of the var changes.
If you are taking a number as an input, you can check if the number is int, float or long.
Write a python program to check if a variable is an integer or a string using isinstance()?
var = input("Enter the value: ")
if(isinstance(var, float)):
print "var is float."
elif(isinstance(var, int)):
print "var is integer."
elif(isinstance(var,long)):
print "var is loog."
else
print "Unknow data type"
Method 2: Using type()
function:
We saw earlier identifying the type of the variable using the type()
function. You can also use it to check the type of variable using the type()
method and perform an action based on its type.
Write a python program to check if a variable is an integer or a string using type().
var = input("Enter the value: ")
if type(var).__name__ == 'str':
print "var is a string!"
elif type(var).__name__ == 'list':
print "var is a list!"
The above program checks the list and string type. You can use all other data types in the conditional operator.
Python Code to check and identify the class of the object
You can use the above two methods to identify the object of the particular class.
1) Using type
fucntion:
class MyFirstClass:
var = 10
obj = MyFirstClass()
type(obj) # __main__.MyFirstClass
2)Using isinstance()
fucntion:
class MyFirstClass:
var = 10
obj = MyFirstClass()
isinstance(obj, MyFirstClass) #True
Wrapping up…
The above two methods isinstance()
and type()
to identify and check the data type of the variable, I find it very convenient to use in my code.
This is all from this tutorial for python to check the type of variable. If you have any queries or point to discuss, comment below.
Happy Pythoning!
Comments
Somnath Samanta
Program does not run
Aniruddha Chaudhari
Hi Somnath,
Can you please mention the Python version you are using and the type of error you are getting?
Aniruddha Chaudhari
As per corrected by Binu David, you are missing “)” in second elif statement of your code.
Vikram
for python 3.8.3
try this program.
Binu David
It appears that you are missing a “)” in your elif statement.
Aniruddha Chaudhari
Thanks Binu for the correcting.
Edited!
christian
Why you still use Python 2?
Aniruddha Chaudhari
Till the last month, I was focus to maintain code for both Python 2 and Python 3. Now onwards, only Python 3.
Subhash
What input I give, the output is “var is str”
Aniruddha Chaudhari
Whatever input you give, input() always takes it as a string. Irrespective of input, the output will be “var is str”.
Subhash
Ok… Thank you Very Much…
Aniruddha Chaudhari
You’re welcome!
Manav
why you used “” for string values?
Aniruddha Chaudhari
You can use either ” or “” for Python string.
vishal
output=enter the value 45
output=var is string
but if independently asked it is giving as:
n=45
isinstance(n,str)
False
Aniruddha Chaudhari
Hi Vishal, when you take a user input using
input()
function, it returns string always.If you want to take an integer as an input from the user, you have to explicitly convert it using
int()
function.For Example,
Dimpal Solanki
This works only for the integer value. But, when I input the float value it will give an error.
Aniruddha Chaudhari
For float value, you can use float() instead of int().
Kyle Sallee
isinstance(n, (str, int, float) #True
seems as if it should be
isinstance(n, (str, int, float)) #True
Aniruddha Chaudhari
Thanks for the correction. We missed the closing bracket.