Sometimes we may require to know the type of the variable in advance to avoid future errors like exception errors in python. There are many methods to know the type of the variable in python. In this tutorial, you will learn how to know the typeof of a variable in python through steps.
Steps on knowing the typeof a variable in python
In this section you will know all the steps you will follow to know the type of the variable.
Step 1: Create a variable
The first step is to create a sample variable that I will use different methods to find the type of the variable.
Let’s create an integer variable using the assignment operator.
sample_variable = 10
Step 2: Use the defined methods
After the variable creations use the following methods to determine the type of the variable.
Method 1: Using the type() function
The first method to find the type of the variable is the use of type() function. Here you will just pass the sample_variable as an argument of this function.
sample_variable = 10 print(type(sample_variable))
Method 2: Find the typeof variable using the isinstance() function
The second method to find the type of the variable is to pass the object and class as an argument to isinstance() function. In this case, the class is int. The function will return true if the sample variable is an instance of that class and false if it is not.
Run the below lines of code to know the type of the variable.
sample_variable = 10 print(isinstance(sample_variable, int))
Method 3 :Using the __class__ attribute:
You can also use the __class__ attribute on any object to find the class or type of that variable. For example, if the variable is of integer type then the class of the variable will be <class ‘int’>
sample_variable = 10 print(sample_variable.__class__)
Method 4: Use the built-in function isnumeric()
The other method to find the type of the variable is the use of the built-in function of the string variable. For example, you will use the isnumeric() function to determine whether the variable is numeric or not on the string input. It will return true or false if the variable is numeric or not.
Run the below lines of code to check the type of the variable.
sample_string = "Data Science Leaner" print(sample_string.isnumeric())
It’s best to find the type of a variable when you wants to take input from the user to avoid the error in the future. You can take the example of the machine learning model. Here you have to make sure that you will take the input for the prediction of the same type as you have modeled. Using the above methods you are able to find the typeof the variable in python.
I hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.