Skip to content

    Chapter 13, Basic

    Input, output and operators

    With `print`, `input`, and the operators you already write programs that talk to the person and do calculations.

    Code for this chapter: basico/cap13_entrada_operadores.py

    print

    The print accepts several values and two parameters that I use a lot: sep (separator) and end (what comes at the end, the newline by default):

    basico/cap13_entrada_operadores.pylinhas 10 a 12
    print("a", "b", "c", sep="-")
    print("sem quebra", end=" ")
    print("de linha")
    
    Output
    a-b-c
    sem quebra de linha
    

    input

    The input shows a question, waits for the person to type, and returns always a string. If you need a number, convert:

    basico/cap13_entrada_operadores.pylinhas 17 a 19
    nome = input("Qual é o seu nome? ")
    idade = int(input("Quantos anos você tem? "))
    print(f"Olá, {nome}. Em 5 anos você terá {idade + 5} anos.")
    
    Output
    Qual é o seu nome? Ana
    Quantos anos você tem? 30
    Olá, Ana. Em 5 anos você terá 35 anos.
    

    Never trust what the person types

    If someone types trinta, the int() raises ValueError and the program crashes. In the exceptions chapter, I show how to validate the input without crashing the program.

    Arithmetic operators

    OperatorOperationExampleResult
    + - *Addition, subtraction, multiplication10 - 37
    /Division (always float)10 / 42.5
    //Integer division (rounds down)10 // 42
    %Remainder10 % 42
    **Power2 ** 8256
    basico/cap13_entrada_operadores.pylinhas 24 a 29
    print(10 / 3)
    print(10 // 3)
    print(-7 // 2)
    print(10 % 3)
    print(2 ** 8)
    print(divmod(17, 5))
    
    Output
    3.3333333333333335
    3
    -4
    1
    256
    (3, 2)
    

    Be careful with -7 // 2: integer division rounds down, so the result is -4, and not -3. The divmod returns quotient and remainder at once.

    Comparison and logical operators

    Comparisons can be chained, just like in mathematics:

    basico/cap13_entrada_operadores.pylinhas 34 a 37
    x = 7
    print(1 < x < 10)
    print(x == 7.0)
    print("a" < "b")
    
    Output
    True
    True
    True
    

    The operators and, or and not have two characteristics that most courses do not mention. First, and and or return one of the operands, not necessarily True or False. Second, they perform short-circuiting: they stop as soon as the result is determined.

    basico/cap13_entrada_operadores.pylinhas 39 a 43
    nome = "" or "anônimo"
    print(nome)
    print(0 and 5)
    print(3 and 5)
    print(not [])
    
    Output
    anônimo
    0
    5
    True
    

    The language valor or padrao is common to define a default value. Use with caution: it also swaps 0 and "", which can be valid values.

    Membership and identity

    The operators in and not in ask if an item is in a collection. The operators is and is not ask if two names point to the same object. Use is only with None, True and False:

    basico/cap13_entrada_operadores.pylinhas 48 a 50
    print("py" in "python", 3 not in [1, 2])
    valor = None
    print(valor is None, valor is not None)
    
    Output
    True True
    True False
    

    Compound assignment and the walrus operator

    The operators +=, -=, *=, //= and friends modify and assign at once. The operator := (called the walrus, available since Python 3.8) assigns within an expression:

    basico/cap13_entrada_operadores.pylinhas 55 a 62
    total = 10
    total += 5
    total *= 2
    total //= 4
    print(total)
    
    if (n := len("python")) > 5:
        print(f"{n} caracteres")
    
    Output
    7
    6 caracteres
    

    When an expression mixes operators, precedence decides the order: first **, then * / // %, then + -, then comparisons, then not, and and or. I never memorize the entire table: I use parentheses whenever the order is not obvious at first glance.

    Exercise 1

    Convert seconds into hours, minutes, and seconds

    Write decompor(segundos) that returns a tuple (horas, minutos, segundos). For example, 3725 seconds are (1, 2, 5).