Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / Python

Uvjetno grananje

if i sljedeći elif ispituju uvjete redom i izvode prvu granu s istinitim uvjetom.

Verzija: Python 3.14; repository image, production runtime not attested

Sintaksa

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

if i sljedeći elif ispituju uvjete redom i izvode prvu granu s istinitim uvjetom.

else obrađuje preostali slučaj. Prazne zbirke i nula imaju neistinitu vrijednost. Objekt može definirati __bool__ ili, ako ga nema, __len__.

Kod praznog popisa funkcija se vraća prije čitanja items[0]. Rezultati su empty, negative i 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])

Primjeri

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])])

Rezultat

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

Kod praznog popisa funkcija se vraća prije čitanja items[0]. Rezultati su empty, negative i other.

Izvori