Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Loops and iteration

A for loop consumes an iterator, while a while loop retests its condition before every iteration.

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

Syntax

for item in iterable:
    process(item)
while condition:
    update()

A for loop consumes an iterator, while a while loop retests its condition before every iteration.

continue advances to the next iteration. break exits the innermost loop and skips its else. Normal exhaustion or a false condition reaches else even when the body never ran.

The first even value is 4. Odd-only and empty inputs both take the else branch and return None.

counter=2
seen=[]
while counter:
    seen.append(counter)
    counter-=1
else: seen.append('done')
assert seen==[2,1,'done']
g=iter([1,2,3])
for n in g:
    if n==2: break
assert list(g)==[3]

Examples

def first_even(values):
    for n in values:
        if n % 2:
            continue
        break
    else:
        return None
    return n

print(first_even([1, 4, 6]), first_even([1, 3]), first_even([]))

Result

4 None None

The first even value is 4. Odd-only and empty inputs both take the else branch and return None.

Sources