Python data types are the words that every later lesson depends on. The four you will use all the time are int, float, str, and bool. The surprises are not in what they hold. The surprises are in how they relate to each other. Booleans are integers, integers have no size limit, and floats are only close to the real number. Each of those facts has a line of code that will surprise you if you have not seen it before.
This is the first lesson in the Python Data Types and Variables module, and the next lesson in this module is about "Arithmetic Operators and Operator Precedence".
What are Python's core data types?
Python comes with a small set of built-in types, and most of your code is built out of them. These four cover the simple values, and the rest of the language adds containers for groups of them.
| Type | Example | Mutable | What it is for |
|---|---|---|---|
int | 42 | no | Whole numbers, with no size limit |
float | 3.14 | no | Decimal numbers kept as binary approximations |
str | "forty-two" | no | Text, stored as Unicode characters |
bool | True | no | Two values: true or false |
NoneType | None | n/a | The single "no value here" marker |
values = {
'count': 42,
'ratio': 3.14,
'label': 'forty-two',
'flag': True,
'missing': None,
'items': [1, 2, 3],
}
for name, value in values.items():
print(name, 'holds', repr(value), 'and its type is', type(value).__name__)
Every value knows its own type while the program runs. You never declare a type yourself, and the type of a variable can change between assignments. That is why the same value can behave like a number on one line and like text on the next.
How do you check the type of a value?
Three tools, from the simple one to the detailed one. type(value) returns the exact class of the value. isinstance(value, some_type) asks whether the value is an instance of that class or of any class below it. And the inheritance chain of a class shows you every parent that it has, which is how you find surprising relationships between types.
value = 42
print('type(value) ->', type(value))
print('isinstance(value, int) ->', isinstance(value, int))
# The chain of parent classes for a type.
print('int.__mro__ ->', int.__mro__)
print('bool.__mro__ ->', bool.__mro__)
Those two chains are the whole story of the next section. bool inherits from int, so isinstance(True, int) is True, even though type(True) is bool.
Use isinstance() instead of type(x) is int in normal code, because it keeps working when somebody later makes a subclass. Use the exact check only when the difference really matters, such as when a flag must not be accepted where a number is expected.
Why is bool a subclass of int?
Because Python treats a boolean as the number zero or the number one. That is handy in arithmetic, and it is also a trap, because True quietly acts like 1 in almost every number context.
print('True == 1 ->', True == 1)
print('True + True ->', True + True)
print('sum([True, False]) ->', sum([True, False]))
print('type(True) is int ->', type(True) is int)
print('isinstance(True, int) ->', isinstance(True, int))
print('isinstance(True, bool) ->', isinstance(True, bool))
print('bool(1) and bool(0) ->', bool(1), bool(0))
print('bool("False") ->', bool('False'))
print('bool("") ->', bool(''))
print('bool([]) ->', bool([]))
print('bool([0]) ->', bool([0]))
Read that output carefully, because it contains the trap. bool('False') is True, because a string with any text in it is truthy, whatever that text says. Empty containers are falsy, and a container that holds a zero is truthy, because the container itself is not empty. This is the cause of the classic bug where a form field that contains the text "False" is treated as a ticked box.
The practical rule is short: use is True or is None when you want to test the exact value, and never let the contents of a string decide something important.
Where do numbers surprise you?
In two ways, and both of them are worth understanding rather than memorising.
The first one is that integers have no upper limit. A Python integer grows as large as you need it to be, so a calculation that would overflow a fixed-size integer in another language simply keeps working. The second one is that floats are binary approximations. Decimal fractions such as 0.1 cannot be stored exactly in binary, and that produces the famous output that surprises everybody once.
import math
import sys
from decimal import Decimal
# Integers have no upper limit.
print('10 ** 40 ->', 10 ** 40)
# Floats cannot hold 0.1 exactly.
total = 0.1 + 0.2
print('0.1 + 0.2 ->', total)
print('== 0.3 ->', total == 0.3)
print('isclose ->', math.isclose(total, 0.3))
print('largest float ->', sys.float_info.max)
# Decimal keeps money exact.
print('Decimal total ->', Decimal('0.10') + Decimal('0.20'))
print('float total ->', 0.10 + 0.20)
For measurements, floats are exactly right, and you should compare them with math.isclose() instead of ==. For money, use decimal.Decimal and build it from a string, as in Decimal('0.10'). If you build it from a float instead, you inherit the very error that you were trying to avoid in the first place.
How do you pick the right type?
intfor counts, indexes, IDs, and anything that must be exact. Integer maths is exact and it is fast.floatfor measurements, ratios, and averages, where a tiny error is perfectly acceptable.Decimalfor money and for anything a customer will be charged. It stores decimal digits exactly.strfor text, and also for numbers that arrive from the outside world as text, which is most of the time.boolfor real yes-or-no values. Do not use0and1as booleans in code that you will read later.
Two habits keep types honest. Print type(value).__name__ when a value surprises you, and compare values with repr() when the difference is invisible in normal output, because repr shows the quotes and escapes that reveal hidden characters.
It also helps to remember that str() and repr() are not the same function. str() asks an object for the version that is meant for people to read. repr() asks for the version that is meant for developers, and that one is more exact. For a float they usually agree. For a string they do not, because repr() adds the quotes that let you see an accidental trailing space.
import sys
def describe(value):
print(type(value).__name__, '|', repr(value), '|', sys.getsizeof(value), 'bytes')
for candidate in (0, 42, 3.14, 'hello', True, None, [1, 2], {'a': 1}):
describe(candidate)
The byte counts are rough, and they change between builds and systems, so treat them as a comparison and not as a promise. What the list shows well is that a small number and a small string cost far less memory than a list holding the same items. That matters when you process a lot of data.
Your turn: build a type detective
- Write a function
classify(value)that returns a short label for any value: "empty text", "whole number", "decimal number", "yes or no", "nothing", "list", or "something else". - Give it a careful mix of inputs:
0,-7,3.0,3.5,'','0',False,None,[],[0],{}, andset(). Print each label next to the value and its type name. - Add a guard so that
Trueis reported as "yes or no" and never as "whole number", even though it passesisinstance(value, int). Put the most specific check first. - Now handle money. Write
add_prices(a, b)that takes two strings, converts them withDecimal, and returns the exact sum. Check thatadd_prices('0.10', '0.20')gives exactly0.30. - Finally, compare
0.1 + 0.2 == 0.3withmath.isclose(0.1 + 0.2, 0.3)in your script and print both. Understanding why one says False and the other says True is the point of this exercise.
The mental model to keep
- Every value knows its own type while the program runs, and you never declare one.
type()is exact andisinstance()understands inheritance. For booleans the two answers differ.- Booleans are integers, so
Trueequals 1 and a non-empty string like "False" is truthy. - Integers are exact and they have no limit. Floats are binary approximations, so compare them with
math.isclose(). - Money belongs to
Decimal, and you build it from a string.