Learn Python by Building Data Science Applications
上QQ阅读APP看书,第一时间看更新

The type function

The type function returns the type of variable that was passed to it. As in the following example, for the string variable, it will return str; for the number variable, int or float, and so on and so forth: 

>>> type(‘Hello world')
str

Here, the function returns the type of the Hello world value, which is a string. This function allows us to differentiate between values, even if this is not very clear. Take a look at the following example:

>>> type(101)
int

>> type('101')
str

Here, type identifies the fact that similar looking values are an integer and a string. Often, however, we don't need to know the specific type of the value, but rather whether the value is of a certain type (and adjust our methods accordingly). For this, there is isinstance.