. Advertisement .
. Advertisement .
Python is one of the most popular programming languages in the world today. In fact, it’s one of the most used programming languages across the globe. However, if you need to check variable type in Python, then this blog will show you how to do that. Read on.
Python variables and their types
1. Python String Variable
stringVariable = "This is a string" print(stringVariable)
2. Python Boolean Variable
boolVariable = True print(boolVariable)
3. Python Float Variable
floatVariable = 50.80 print(floatVariable)
4. Python Integer Variable
intVariable = 50 print(intVariable)
Hopefully, you’ve grasped the concept of a variable and its type.
How Can You Check Variable Type in Python?
Option 1: Utilize type()
You can use type() to check variable type in Python with this approach.
num = 123 print(type(num)) num = 12.53 print(type(num)) num = "hello" print (type(num))
<class 'int'> <class 'float'> <class 'str'>
You can quickly determine the type of variable using this approach.
Option 2: Utilize isinstance()
In Python, this technique is also used to examine the type of a variable.
isinstance(object , classtype)
An object that is being compared to classtype. If the type matches, it returns true; or else, it returns false.
age = isinstance(24,int) print("age is an integer:", age) weight = isinstance(44.5,float) print("weight is a float:",weight)
age is an integer: True weight is a float: True
As you may see, if your type of data is correct, it will return true; or else, it will return false. Therefore, these techniques can be used to determine the type of variable in Python.
What are the differences between type() and isinstance() methods?
We can utilize either method as they are both equally effective in achieving the expected result but we need consider some of the distinctions between them.
class Parent: pass class Child(Parent): pass x1 = Parent() print(type(x1)) x2 = Child() print(type(x2))
<class '__main__.Parent'> <class '__main__.Child'>
class Parent: pass class Child(Parent): pass x1 = Parent() x2 = Child() print(type(x1) is Child) print(type(x1) is Parent) print(isinstance(x2,Child)) print(isinstance(x2,Parent))
False True True True
It is evident from the result above that the type() function only gives True if the exact type matches, whereas the isinstance() method returns True if the type matches with both the Derived and Base classes.
So, we can draw the following conclusion:
If we want to know the precise type, we can use type().
If we wish to identify the type while taking inheritance into account, let’s use isinstance().
We hope you enjoyed our blog about ”How to check variable type in Python”. If you have any other questions or concerns about this issue, please leave a comment below. Thank you for reading; we are always excited when one of our posts can provide useful information on a topic like this!