Chapter 4

Data Types

Interact

Every value has a type, and the built-in type function returns the type of the value of any expression.

type(3)
int
type(3 + .1)
float

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
int

Similarly, the type of a function call is the return value of the call, and there is no function_call type.

type(abs(-3))
int

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)
builtin_function_or_method

We have also imported the math module. Once they're imported, modules are values and have their own type.

import math
type(math)
module

However, things inside modules have their own types:

type(math.log)
builtin_function_or_method

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)
3
float(3)
3.0
type(int(3.1))
int

This chapter will explore other useful types of data.

results matching ""

    No results matching ""