Skip to content

Informatics Practices · Ch 3 — Brief Overview of Python

Number

3.5.1

Number

The Number data type is Python's home for numerical values — it stores numbers and nothing else. Within this one family, Python distinguishes three different types, because whole numbers, decimal numbers and complex numbers are stored and handled differently: int, float and complex.

Type/ClassDescriptionExamples
intinteger numbers-12, -3, 0, 123, 2
floatfloating point numbers-2.04, 4.0, 14.23
complexcomplex numbers3 + 4i, 2 - 2i

A few observations sharpen the table. Integers are whole numbers, positive, negative or zero — no decimal point. Floating point numbers carry a decimal part, and the presence of the point is what makes them float: 4.0 is a float even though its value is a whole number, because it is written with a decimal point. Complex numbers have a real part and an imaginary part, as in 3 + 4i.

Python adds one more numeric type with a special status: the Boolean type, written bool, which is a subtype of integer. It is a unique data type consisting of exactly two constants, True and False. The connection to integers is precise — the Boolean True value is non-zero, and Boolean False is the value zero. So truth in Python is literally built on top of numbers: False corresponds to zero, True to non-zero.

Important

bool is a subtype of int, with exactly two constants: True (non-zero) and False (the value zero). Remember the capital letters — True and False are keywords and must be written exactly so.

How do you find out which type a value actually has? Python provides the built-in function type() for exactly this, and the interactive mode is the natural place to try it. Type an assignment, then ask for the variable's type:

>>> quantity = 10
>>> type(quantity)
<class 'int'>
>>> price = -1921.9
>>> type(price)
<class 'float'>

The interpreter's replies are worth reading carefully. quantity was assigned the whole number 10, so its type comes back as <class 'int'>. price was assigned -1921.9, a number with a decimal part, so its type is <class 'float'>. Notice that nowhere did we declare these types ourselves — Python inferred each variable's type from the value assigned to it, and type() simply reports the result.

Tip

Whenever you are unsure what kind of value a variable holds, pass it to type() in interactive mode. It is the quickest way to confirm whether a value is an int, a float, a string, or something else — especially when a value like "452" looks numeric but is actually text. …

Table 3.2Numeric data types
Type/ ClassDescriptionExamples
intinteger numbers-12, -3, 0, 123, 2
floatfloating point numbers-2.04, 4.0, 14.23