Skip to content

    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

    TypeWhat it representsExamples
    intIntegers, with no size limit42, -7, 1_000_000
    floatDecimal numbers with limited precision3.14, -0.5
    complexComplex numbers3 + 4j
    strText"olá"
    boolTrue or falseTrue, False
    NoneTypeAbsence of valueNone
    bytesByte sequenceb"abc"
    basico/cap10_tipos.pylinha 10
    print(type(42), type(3.14), type(3 + 4j), type("oi"), type(True), type(None))
    
    Output
    <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:

    basico/cap10_tipos.pylinhas 15 a 16
    print(2 ** 100)
    print(1_000_000)
    
    Output
    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 ==:

    basico/cap10_tipos.pylinhas 18 a 23
    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"))
    
    Output
    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:

    basico/cap10_tipos.pylinhas 28 a 29
    print(True + True)
    print(isinstance(True, int))
    
    Output
    2
    True
    

    None

    None is the only value of type NoneType and means "no value". The correct comparison is always with is:

    basico/cap10_tipos.pylinhas 34 a 35
    resultado = None
    print(resultado is None)
    
    Output
    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.