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:
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))
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:
idade = 20
situacao = "adulto" if idade >= 18 else "menor"
print(situacao)
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:
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"))
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
| Avoid | Prefer |
|---|---|
if ativo == True: | if ativo: |
if len(lista) > 0: | if lista: |
if valor == None: | if valor is None: |
ifs nested in cascade | Early returns |
The early return (guard clause) handles exit cases first and leaves the main path without extra indentation:
def desconto(preco, cliente_vip):
if preco <= 0:
return 0
if not cliente_vip:
return 0
return preco * 0.1
print(desconto(200, True))
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.