Skip to content

Computer Science · Ch 5 — Getting Started with Python

Number

5.7.1

Number

The Number data type stores numerical values only. It is further classified into three different types — int, float and complex.

The three numeric types (Table 5.2)

Type / ClassDescriptionExamples
intinteger numbers-12, -3, 0, 125, 2
floatreal or floating point numbers-2.04, 4.0, 14.23
complexcomplex numbers3 + 4j, 2 - 2j

Boolean — a subtype of integer

The Boolean data type (bool) is a subtype of integer. It is a unique type consisting of just two constants, True and False. The rule for what counts as which:

  • Boolean True is any value that is non-zero, non-null and non-empty.
  • Boolean False is the value zero.

Discovering a value's type with type()

Python's built-in function type() reports the data type of any value or variable. Running a few statements in interactive mode (the textbook's Example 5.3):

>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> num2 = -1210
>>> type(num2)
<class 'int'>
>>> var1 = True
>>> type(var1)
<class 'bool'>
>>> float1 = -1921.9
>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>
>>> var2 = -3+7.2j
>>> print(var2, type(var2))
(-3+7.2j) <class 'complex'>

Three details worth noticing:

  • Positive and negative whole numbers alike are int.
  • The expression -9.8*10**2 evaluates to a float, and the printed value -980.0000000000001 betrays the tiny representation error inherent in floating-point arithmetic — the result is not the exact -980.0 one might expect on paper.
  • A complex number is written with a j part, and printing it shows the value in parentheses along with <class 'complex'>.

From single values to collections …

Table 5.2Numeric data types
Type/ ClassDescriptionExamples
intinteger numbers–12, –3, 0, 125, 2
floatreal or floating point numbers–2.04, 4.0, 14.23