Skip to content

    Chapter 14, Basic

    Conditionals

    Useful programs make decisions. The `if` is the tool, and writing clean conditions is the skill.

    Code for this chapter: basico/cap14_condicionais.py

    if, elif and else

    Python tests conditions from top to bottom and executes only the first true block. Indentation defines the block:

    basico/cap14_condicionais.pylinhas 10 a 24
    def classificar(nota):
        if nota >= 9:
            return "excelente"
        elif nota >= 7:
            return "bom"
        elif nota >= 5:
            return "regular"
        else:
            return "insuficiente"
    
    
    print(classificar(9.5))
    print(classificar(7))
    print(classificar(5))
    print(classificar(2))
    
    Output
    excelente
    bom
    regular
    insuficiente
    

    Conditional expression

    To choose between two values in one line, there is the form valor_se_verdadeiro if condicao else valor_se_falso:

    basico/cap14_condicionais.pylinhas 29 a 31
    idade = 20
    situacao = "adulto" if idade >= 18 else "menor"
    print(situacao)
    
    Output
    adulto
    

    match: pattern matching

    Since Python 3.10 there is the match, which is much more than a switch. It combines the form of the data, and can capture parts of it:

    basico/cap14_condicionais.pylinhas 36 a 51
    def responder(comando):
        match comando.split():
            case ["parar"]:
                return "parando"
            case ["mover", direcao]:
                return f"movendo para {direcao}"
            case ["mover", direcao, passos] if passos.isdigit():
                return f"movendo {passos} passos para {direcao}"
            case _:
                return "comando desconhecido"
    
    
    print(responder("parar"))
    print(responder("mover norte"))
    print(responder("mover sul 3"))
    print(responder("voar"))
    
    Output
    parando
    movendo para norte
    movendo 3 passos para sul
    comando desconhecido
    

    The case _ is the default case. I use match when the data has structure (commands, messages, trees). To compare a value with a few simple options, if and elif remain more straightforward.

    Languages that keep the code clean

    AvoidPrefer
    if ativo == True:if ativo:
    if len(lista) > 0:if lista:
    if valor == None:if valor is None:
    ifs nested in cascadeEarly returns

    The early return (guard clause) handles exit cases first and leaves the main path without extra indentation:

    basico/cap14_condicionais.pylinhas 56 a 64
    def desconto(preco, cliente_vip):
        if preco <= 0:
            return 0
        if not cliente_vip:
            return 0
        return preco * 0.1
    
    
    print(desconto(200, True))
    
    Output
    20.0
    

    Exercise 1

    Leap year

    Write eh_bissexto(ano). A year is a leap year if it is divisible by 4, except for those divisible by 100, unless they are also divisible by 400.

    Exercise 2

    Temperature ladder

    Write descrever(temperatura) that returns "frio" below 10 degrees, "agradável" below 28 and "quente" from there.