Pular para o conteúdo principal
eLearner.app
Módulo 2 · Lição 3 de 47/36 no curso~10 min
Lições do módulo (3/4)

quebrar, continuar e mais em loops

Inside a loop (both for and while) you can alter the normal flow with three constructs:

  • breakexits the loop immediately.
  • continueskips the rest of the body and jumps to the next iteration.
  • else (on the loop) — executed when the loop terminates without a break.

break

Python
for n in [3, 7, 11, 4, 9]:
    if n % 2 == 0:
        primo_pari = n
        break
primo_pari  # 4

break stops the loop as soon as possible. Anything after break in the current iteration's body is NOT executed.

continue

Python
risultati = []
for n in range(1, 11):
    if n % 2 == 0:
        continue   # skip evens
    risultati.append(n * n)
risultati  # [1, 9, 25, 49, 81]

Think of continue as "go to the next iteration". It is used to filter items without adding one more indentation level.

else on the loop (Pythonic idiom)

A Python peculiarity: loops can also have an else, executed only if the loop terminated naturally (without break). It is perfect for searches:

Python
target = 7
for n in [2, 4, 6, 8]:
    if n == target:
        trovato = True
        break
else:
    trovato = False
trovato  # False

Read it as: "for each n in the list; if you take the break branch, skip the else; otherwise execute the else".

Nested loops: break exits only the innermost one

Python
for x in range(3):
    for y in range(3):
        if x == y == 1:
            break
        print(x, y)

break exits only the for y, not the for x. To exit both you must use a flag or a function + return.

The unusual loop...else construct

In Python, both for and while loops can feature an optional else clause. The else block is executed only if the loop completes normally (i.e. without encountering a break statement). This is very helpful for search algorithms (e.g. "search for an element: if found, break; else, report that it was not found").

Try it yourself

Exercício#python.m2.l3.e1
Tentativas: 0Carregando…

Given the list `numbers = [10, 15, 20, 25, 30, 35]`, find the first number divisible by 7 and assign it to `result`. If none exists, assign -1.

Carregando editor…
Mostrar dica

35 is the first (and only) one divisible by 7 in the list.

Solução disponível após 3 tentativas

Review exercise

Exercício#python.m2.l3.e2
Tentativas: 0Carregando…

Build the list `odd_numbers` with the odd numbers from 1 to 20 (inclusive) using a for loop over range(1, 21) and continue to skip the evens.

Carregando editor…
Mostrar dica

If n is even, continue; otherwise append.

Solução disponível após 3 tentativas

Additional challenge

Exercício#python.m2.l3.e3
Tentativas: 0Carregando…

Given the list `numbers = [7, 11, 14, 21, 25]`, write a `for` loop to find the first number that is divisible by 7 and also strictly greater than 10. When you find it, store it in `found` and exit the loop using `break`. Finally, evaluate `found`.

Carregando editor…
Mostrar dica

Inside the loop, check if num % 7 == 0 and num > 10:, assign it to found and trigger break.

Solução disponível após 3 tentativas