Chapter 4
Data Types
Every value has a type, and the built-in type
function returns the type of the value of any expression.
type(3)
type(3 + .1)
The type
of an expression is the type of its final value. So, the type
function will never indicate that the type of an expression is a name, because names are always evaluated to their assigned values. (There is no name
type at all.)
x = 3
type(x) # The type of x is an int, not a name
Similarly, the type of a function call is the return value of the call, and there is no function_call
type.
type(abs(-3))
Stranger types¶
Another type we have encountered already is a built-in function. Python indicates that the type is a builtin_function_or_method
; the distinction between a function and a method is not important at this stage.
type(abs)
We have also imported the math
module. Once they're imported, modules are values and have their own type.
import math
type(math)
However, things inside modules have their own types:
type(math.log)
Can you guess what type(type)
is? Try it yourself to check!
(If you guessed builtin_function_or_method
, you guessed well, but you were nevertheless incorrect. Sometimes Python is just inscrutable.)
Converting between types¶
Sometimes it's possible to convert data from one type to another. The int
and float
functions (somewhat confusingly given the same names as the two numerical types) attempt to convert their arguments to integers and floating-point numbers, respectively:
int(3.1)
float(3)
type(int(3.1))
This chapter will explore other useful types of data.