Skip to content

    Chapter 9, Basic

    Comments and variables

    A variable in Python is not a box that holds a value. It is a name that points to an object, and this difference explains a lot further on.

    Code for this chapter: basico/cap09_variaveis.py

    Comments

    Comments are notes for those reading the code. Python ignores everything that comes after a #, until the end of the line.

    basico/cap09_variaveis.pylinhas 10 a 17
    # Comentário de uma linha
    idade = 30  # comentário no fim da linha
    
    """
    Isto é uma string de várias linhas.
    O Python a avalia e descarta, mas ela não é um comentário de verdade.
    """
    print(idade)
    
    Output
    30
    

    Python does not have multi-line comments. What people do is use a triple-quoted string as if it were a comment. It works, but it is a loose string in the code. When this string is the first statement of a function, class, or module, it becomes a docstring, the official documentation of that object:

    basico/cap09_variaveis.pylinhas 19 a 24
    def area_quadrado(lado):
        """Devolve a área de um quadrado de lado dado."""
        return lado * lado
    
    
    print(area_quadrado.__doc__)
    
    Output
    Devolve a área de um quadrado de lado dado.
    

    I write comments to explain why, never what. The code already says what it does. The comment says the reason for the decision.

    Variables are names

    In Python, idade = 30 does not "store 30 in age". It creates the integer object 30 and makes the name idade point to it. The type belongs to the object, not to the name. That's why the same name can point to different types throughout the program:

    basico/cap09_variaveis.pylinhas 29 a 37
    nome = "Ana"
    idade = 30
    cidade = "Recife"
    print(nome, idade, cidade)
    
    valor = 10
    print(type(valor))
    valor = "dez"
    print(type(valor))
    
    Output
    Ana 30 Recife
    <class 'int'>
    <class 'str'>
    

    This view of a label (name pointing to object) will be decisive when we get to lists and functions. Keep it in mind.

    Multiple assignments and swapping values between two variables become natural:

    basico/cap09_variaveis.pylinhas 39 a 44
    a, b = 1, 2
    a, b = b, a
    print(a, b)
    
    x = y = 0
    print(x, y)
    
    Output
    2 1
    0 0
    

    Valid names and conventions

    A name starts with a letter or underscore, contains letters, numbers, and underscores, distinguishes between uppercase and lowercase, and cannot be a reserved word. The module keyword knows all the reserved words:

    basico/cap09_variaveis.pylinhas 49 a 53
    import keyword
    
    print(keyword.iskeyword("class"))
    print(keyword.iskeyword("nome"))
    print(len(keyword.kwlist) > 30)
    
    Output
    True
    False
    True
    
    ElementConvention (PEP 8)Example
    Variables and functionssnake_casepreco_total
    ConstantsMAIUSCULAS_COM_SUBLINHADOLIMITE_DE_TENTATIVAS
    ClassesPascalCaseContaBancaria
    Internal useprefix __cache

    Python does not have true constants

    Writing LIMITE = 3 in uppercase is a warning to others that the value should not change. The language does not prevent the change. There is typing.Final for static analysis tools, and I show it in the type hints chapter.

    Exercise 1

    Swap two values without creating a third variable

    Data a = 3 and b = 7, swap the values so that a ends up being 7 and b being 3.