Chapter 10, Basic
Data types
Every value has a type, and the type decides what you can do with it. Python discovers the type on its own, but that doesn't mean you can ignore it.
Code for this chapter: basico/cap10_tipos.py
The basic types
| Type | What it represents | Examples |
|---|---|---|
int | Integers, with no size limit | 42, -7, 1_000_000 |
float | Decimal numbers with limited precision | 3.14, -0.5 |
complex | Complex numbers | 3 + 4j |
str | Text | "olá" |
bool | True or false | True, False |
NoneType | Absence of value | None |
bytes | Byte sequence | b"abc" |
print(type(42), type(3.14), type(3 + 4j), type("oi"), type(True), type(None))
<class 'int'> <class 'float'> <class 'complex'> <class 'str'> <class 'bool'> <class 'NoneType'>
Unlimited integers, limited decimals
The int in Python grows until memory runs out. The underscore helps to read large numbers:
print(2 ** 100)
print(1_000_000)
1267650600228229401496703205376
1000000
The float follows the IEEE 754 binary standard and does not exactly represent most decimal fractions. This applies to any language, and it's the reason why you should never compare money with ==:
from decimal import Decimal
import math
print(0.1 + 0.2)
print(math.isclose(0.1 + 0.2, 0.3))
print(Decimal("0.1") + Decimal("0.2"))
0.30000000000000004
True
0.3
To compare decimals use math.isclose. For money, use Decimal (or work with cents in integers).
bool is an int type
For historical reasons, bool is a subclass of int. This explains a classic gotcha and matters when testing types:
print(True + True)
print(isinstance(True, int))
2
True
None
None is the only value of type NoneType and means "no value". The correct comparison is always with is:
resultado = None
print(resultado is None)
True
Exercise 1
Classify the type of a value
Write tipo_de(valor) that returns "nulo", "booleano", "inteiro", "decimal", "texto" or "outro". Remember that True is also int.