Lompati ke konten utama
eLearner.app
Modul 2 · Pelajaran 3 dari 47/36 dalam kursus~10 min
Pelajaran modul (3/4)

istirahat, lanjutkan dan lainnya dalam loop

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

Latihan#python.m2.l3.e1
Upaya: 0Memuat…

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.

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Review exercise

Latihan#python.m2.l3.e2
Upaya: 0Memuat…

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.

Memuat editor…
Tunjukkan petunjuk

If n is even, continue; otherwise append.

Solusi tersedia setelah 3 upaya

Additional challenge

Latihan#python.m2.l3.e3
Upaya: 0Memuat…

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`.

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya