Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

Controlo de fluxo condicional

if e os elif seguintes avaliam as condições por ordem e executam o primeiro ramo verdadeiro.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

if condition:
    first()
elif alternative:
    second()
else:
    fallback()

if e os elif seguintes avaliam as condições por ordem e executam o primeiro ramo verdadeiro.

else trata o caso restante. As coleções vazias e o zero são falsos. Um objeto pode definir __bool__ ou, na sua ausência, __len__.

Com a lista vazia a função devolve antes de ler items[0]. Os resultados são empty, negative e other.

events=[]
def check(n):
    events.append(n)
    return n
if check(0): raise AssertionError
elif check(1): pass
elif check(2): raise AssertionError
assert events==[0,1]
class Switch:
    def __bool__(self): return False
assert not Switch() and not [] and bool([0])

Exemplos

def classify(items):
    if not items:
        return "empty"
    elif items[0] < 0:
        return "negative"
    else:
        return "other"

print([classify(v) for v in ([], [-2], [0])])

Resultado

['empty', 'negative', 'other']

Com a lista vazia a função devolve antes de ler items[0]. Os resultados são empty, negative e other.

Fontes