• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

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

Aniruddha Chaudhari/115284/20
CodePython

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?

Table of Contents

  • What is the dynamic data type in Python?
  • How to check the data type of the variable?
  • Why is it important to know the data type of variable?
  • Different methods in Python to check the type of variable
    • Method 1: Using isinstance() function:
    • Method 2: Using type() function:
  • Python Code to check and identify the class of the object

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!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Somnath Samanta
    September 8, 2018 at 9:19 pm
    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

    • Reply
      Aniruddha Chaudhari
      September 8, 2018 at 9:31 pm

      Hi Somnath,

      Can you please mention the Python version you are using and the type of error you are getting?

    • Reply
      Aniruddha Chaudhari
      December 9, 2018 at 8:21 am

      As per corrected by Binu David, you are missing “)” in second elif statement of your code.

    • Reply
      Vikram
      May 20, 2020 at 11:47 am

      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.

  • Reply
    Binu David
    December 8, 2018 at 7:33 pm

    It appears that you are missing a “)” in your elif statement.

    • Reply
      Aniruddha Chaudhari
      December 9, 2018 at 8:20 am

      Thanks Binu for the correcting.

      Edited!

  • Reply
    christian
    January 17, 2020 at 7:48 am

    Why you still use Python 2?

    • Reply
      Aniruddha Chaudhari
      January 19, 2020 at 8:59 am

      Till the last month, I was focus to maintain code for both Python 2 and Python 3. Now onwards, only Python 3.

  • Reply
    Subhash
    February 21, 2020 at 10:42 pm
    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”

    • Reply
      Aniruddha Chaudhari
      February 21, 2020 at 10:48 pm

      Whatever input you give, input() always takes it as a string. Irrespective of input, the output will be “var is str”.

      • Reply
        Subhash
        February 23, 2020 at 11:48 am

        Ok… Thank you Very Much…

        • Reply
          Aniruddha Chaudhari
          February 23, 2020 at 1:27 pm

          You’re welcome!

  • Reply
    Manav
    June 29, 2020 at 10:42 pm
    strIn1 = "20"
    strIn2 = "35"
    print('String output: ',strIn1 + strIn2)
    val1 = 20
    val2 = 35
    print('Numeric output: ',val1+val2)
    

    why you used “” for string values?

    • Reply
      Aniruddha Chaudhari
      June 30, 2020 at 9:26 am

      You can use either ” or “” for Python string.

  • Reply
    vishal
    June 29, 2020 at 10:58 pm
    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

    • Reply
      Aniruddha Chaudhari
      June 30, 2020 at 9:36 am

      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"))  
  • Reply
    Dimpal Solanki
    September 27, 2020 at 11:25 pm
    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.

    • Reply
      Aniruddha Chaudhari
      September 28, 2020 at 5:17 pm

      For float value, you can use float() instead of int().

      var=float(input("enter the value"))
      
  • Reply
    Kyle Sallee
    July 6, 2021 at 3:24 am

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

    seems as if it should be

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

    • Reply
      Aniruddha Chaudhari
      July 8, 2021 at 3:39 pm

      Thanks for the correction. We missed the closing bracket.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard