How to Program Python to check type of variable? | float or int or string or class

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.

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 the 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 significance. There are some supported functions for each data type.

Let’s say, we can not do arithmetic operations on string datatype. The concatenation of two objects is valid only for the string.

Sometimes, you may want to manipulate the data based on its data type. So comparing data types in Python is essential.

For example:

I am performing ‘+’ operations on integers as well as on string 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 strings.
  • When I perform ‘+’ operations on the integers, it performs an arithmetic addition operation.

So 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 input.

If the variable (first parameter) is an instance of data type (mentioned as the second parameter), this function returns true.

For example:

avl =16
 
isinstance(val, int) #True
 
isinstance(val, long) #False
 
isinstance(val, str) #False

Here you can also pass the Python tuple as the second argument. The below code checks, if the variable ‘n’ belongs to any of the str, int, or float data type.

val = 17
isinstance(val, (str, int, float) #True

Here is a simple program that takes input from the user and saves it in a variable. 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 function:

class MyFirstClass:
    var = 10
obj = MyFirstClass()
type(obj) # __main__.MyFirstClass

2)Using isinstance() function:

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 points to discuss, comment below.

Happy Pythoning!

20 Comments

  1. 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"
    

    Program does not run

    1. for python 3.8.3

      from numpy import long
      
      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 long.")
      else:
          print("Unknow data type")
      

      try this program.

  2. var = input("Enter the value: ")
    
    if(isinstance(var, float)):
        print( "var is float.")
    elif(isinstance(var, int)):
        print ("var is integer.")
    elif(isinstance(var, complex)):
        print ("var is complex.")
    elif(isinstance(var, str)):
    	print("var is str")
    else:
    	print ("Unknow data type") 
    

    What input I give, the output is “var is str”

  3. strIn1 = "20"
    strIn2 = "35"
    print('String output: ',strIn1 + strIn2)
    val1 = 20
    val2 = 35
    print('Numeric output: ',val1+val2)
    

    why you used “” for string values?

  4. var=input("enter the value")                                             
    
    if (isinstance(var,float)):                                                    
     
        print("var is float")
    
    elif(isinstance(var,int)):
    
        print("var is int")
    
    elif(isinstance(var,str)):
    
        print("var is string")
    
    else:
    
        print("var is unknown")
    

    output=enter the value 45

    output=var is string
    but if independently asked it is giving as:

    n=45

    isinstance(n,str)

    False

    1. 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,

      var=int(input("enter the value"))  
  5. var=int(input("enter the value"))
    

    This works only for the integer value. But, when I input the float value it will give an error.

  6. isinstance(n, (str, int, float) #True

    seems as if it should be

    isinstance(n, (str, int, float)) #True

Leave a Reply

Your email address will not be published. Required fields are marked *