Skip to content
  • Home
  • How To
  • M0
  • Module 1 - Python
  • Agents
  • M2
  • M3
  • M4
  • M5
  • M6
  • Progress
  • Contact
  • Pricing
  • Sign in
  • Future
  1. Module 1M1
  2. ›
    S2Control Flow
  3. ›
    Lesson 4 of 4Controlling Loops - break, continue, and Nesting
  4. ›
    S2›Lesson 4 of 4
  1. Module 1
  2. ›
  3. Section 2
  4. ›
  5. Lesson 4

Controlling Loops - break, continue, and Nesting

FREE·~1.5 h·2 labs·4 questions·1 assignment


Context

Two statements change a loop from the inside. One abandons the loop entirely, the other abandons only the current pass and moves to the next item. Loops also nest, one placed inside the body of another.

Both show up the moment real data does. Stopping early is how you find the first row matching a condition without reading the rest of a large file, and how a search gives up once it has what it came for. Skipping is how a cleaning pass steps over a malformed record and keeps going instead of crashing on it. Nesting is how you walk a table, rows on the outside and the fields of each row on the inside.

The dangerous part is which loop the statement applies to. Inside the inner loop both act on that loop only, so a stop meant to end the whole scan ends one row's worth of work and the outer loop calmly continues, and the result is a run that finishes normally with the wrong answer. Skipping past the step that advances a running total is the same class of error. The previous lesson walked collections start to finish, this lesson interrupts that walk deliberately.


Goal

  • Exit a loop immediately with break the moment a target is found.
  • Skip the rest of a single pass with continue without leaving the loop.
  • Guard break and continue with an if so they fire only when intended.
  • Trace the execution order of a loop nested inside another loop, tracking both counters.
  • Explain why break is the natural tool for "find the first match and stop."

Prerequisites

Neither is required and the lesson assumes you skipped both. They are here only if you would rather see the two statements side by side before meeting them one at a time.

  • YouTube - "Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops" by Corey Schafer. The break and continue portion. Watch for one picture, one statement leaving the loop entirely and the other skipping a single pass.
  • Official docs - The Python Tutorial, "break and continue Statements". The canonical reference for both statements, with the loop-else this lesson only mentions in the section directly below it.

Table of Contents

  • break
  • continue
  • Nested Loop

Theory

break

What. break immediately exits the innermost loop it is inside, abandoning any remaining items or passes and jumping to the first line after the loop. A finally block around it still runs on the way out, covered in Lesson 1.6.2, and so does the closing step of a with block around it, covered in Lesson 1.5.2. Why. Many tasks are "search until you find one, then stop", the first invalid row, the first matching record, the first epoch that converges. Once found, continuing is wasted work, and break is how you stop the moment the answer arrives. When. Use break whenever finishing the loop is pointless after a certain condition is met, almost always inside an if that detects that condition.

Nothing needs installing, break is a keyword built into the language. It is almost always guarded by an if: the loop runs normally until the if condition is met, and then break ends the loop on the spot.

# Search for the first value greater than 50, then stop.
for value in range(0, 100, 10):  # 0, 10, 20, ... 90
    print("checking", value)
    if value > 50:
        print("found", value)
        break                    # leave the loop immediately
print("done")

The loop checks 0 through 50, all of which fail the test, then reaches 60 and exits on the spot. The point is what does not happen: 70, 80 and 90 are never checked at all. Without the break the loop would keep examining values long after the answer was already in hand.

break works identically in a while loop, where it is often the cleanest way to stop, you write while True: (a deliberate "loop forever") and rely on a break inside to end it when the real condition is met.

# 'while True' loops forever UNTIL a break stops it.
attempt = 0
while True:
    attempt += 1
    print("attempt", attempt)
    if attempt >= 3:
        break  # the only exit from this loop
print("stopped after", attempt, "attempts")

This pattern earns its place when the stopping condition is most naturally checked in the middle of the body rather than at the top. Note what the break has become here: it is the loop's only exit, so the variant from Lesson 1.2.2 is still attempt, now moving toward the break's guard instead of toward a false condition.

DON'T:

  • DON'T expect break to exit more than one loop, it leaves only the innermost loop it sits in.
  • DON'T write while True: without a reachable way out inside, such as a break, that is a genuine infinite loop.

continue

What. continue skips the rest of the current pass, except a finally block around it, and jumps straight to the loop's next iteration. The loop keeps running, only the remainder of this one pass is abandoned. Why. It lets you cleanly skip items that should not be processed, missing values, rows that fail a filter, irrelevant entries, without wrapping the whole rest of the body in an if. It keeps the "skip this one" logic at the top and the real work un-indented below. When. Use continue to ignore certain items mid-loop while still processing all the others, the "filter out and move on" pattern.

Like break, continue is almost always guarded by an if. The difference is decisive: break leaves the loop entirely, while continue only skips to the next pass and the loop carries on.

# Process only the odd numbers, skip the even ones.
for n in range(1, 8):       # 1..7
    if n % 2 == 0:          # even?
        continue            # skip the rest of THIS pass, go to next n
    print("processing", n)  # runs only for odd n

Only the odd numbers 1, 3, 5, 7 are processed, and the loop never stops early, it simply ignores the even passes. Put a break where that continue is and the whole loop would have ended at 2, having processed exactly one value. Same guard, same position, completely different outcome.

continue is especially valuable for skipping bad data early, keeping the main work readable.

# Skip missing values (None), accumulate the rest.
total = 0
for reading in [3, None, 7, None, 5]:     # a list of values, some missing as None (lists covered fully in Section 1.4)
    if reading is None:                   # missing data?
        continue                          # skip it, do not add to total
    total += reading                      # only real readings reach here
print("total of valid readings:", total)  # total of valid readings: 15  (3 + 7 + 5)

What the continue buys here is flatness. The rejection sits at the top of the body and the real work stays at the base indentation, where the alternative, if reading is not None: wrapped around everything else, pushes the entire body one level deeper. With one guard that is a small difference, and it compounds fast once there are three.

DON'T:

  • DON'T confuse continue with break, continue skips one pass and keeps looping, break ends the loop.
  • DON'T put essential cleanup after a continue in the same pass, anything below the continue except a finally block is skipped for that iteration.

Nested Loop

What. A nested loop is a loop placed inside the body of another loop. The inner loop runs completely, all of its passes, on every pass of the outer loop that reaches it, unless something ends it early, as a break does. Why. Two-dimensional work needs two loops: every combination of two things (each learning rate with each batch size), every cell of a grid (each row crossed with each column). The nested loop is how you visit every pair. When. Use nesting whenever the task is "for each X, do something with every Y", pairing, gridding, or comparing all combinations of two collections.

The multiplication of passes is the key fact: if the outer loop runs m times and the inner runs n times, the inner body runs m * n times total. Tracing a nested loop means tracking two counters at once.

# Outer loop runs 3 times, inner loop runs 2 times PER outer pass -> 6 total.
for row in range(3):      # row = 0, 1, 2
    for col in range(2):  # col = 0, 1  (restarts every outer pass)
        print("cell", row, col)

Six cells come out in this order: (0,0), (0,1), (1,0), (1,1), (2,0), (2,1). The rightmost number moves fastest, which is the signature of nesting, and it happens because the inner loop restarts from the beginning on every outer pass. Reading it aloud as "row 0 with each col, then row 1 with each col" is how you trace one correctly.

A concrete, ML-flavored use is a small grid search: trying every combination of two hyperparameters. The outer loop picks one setting, the inner loop pairs it with every setting of the other.

# Grid search: every learning rate paired with every batch size.
for lr in [0.1, 0.01]:                   # 2 learning rates (a list of values)
    for batch in [16, 32, 64]:           # 3 batch sizes, restarts each outer pass
        print("lr", lr, "batch", batch)  # runs 2 * 3 = 6 times

This 2 * 3 = 6 pairing is exactly how you would scan a small hyperparameter grid by hand.

Now the rule that matters most once loops are nested: break and continue affect only the innermost loop they sit in. A break in the inner loop ends that inner loop, and execution picks up right after it, still inside the outer loop, so the outer loop carries on. It does not leave both.

DON'T:

  • DON'T expect a break in the inner loop to exit the outer loop, it only ends the inner one, and the outer loop continues.
  • DON'T reuse the same iteration variable name for both loops, the inner one would overwrite the outer's value mid-pass and corrupt the trace.

Additional

A loop may carry an else clause, the loop-else you met with while, and it pairs with break specifically: the else runs only if the loop finished without hitting a break. That makes it the idiomatic "search, and report if nothing was found" shape, since a break means a match was found and skips the else, while running to exhaustion means nothing matched and the else handles it.


Lab Exercises

Both problems first, then both solutions. Do not peek.

Lab Exercise 1: Stop Early, and Skip the Ones You Do Not Want

Covers the first half (break, continue).

In a script scan.py, loop over range(1, 100) and use break to stop at the first number divisible by both 6 and 8. Print each number you check and the match when you find it, then print "search over" after the loop. Confirm the match is 24, and state in a comment how many numbers were checked and why the loop did not run to 99.

Then, in the same file, loop over range(1, 21) representing scores. Use continue to skip any score that is a multiple of 3, and use break to stop the whole scan the moment you reach a score greater than 15. Print every score you actually process. In a comment, list the processed scores and explain how the two statements interacted, in particular why the scan ended where it did rather than at 20.

Lab Exercise 2: Every Pair, and What the Inner break Really Stops

Covers the second half (Nested Loop).

Create pairing.py. Write a nested loop, the outer over epoch in range(1, 4) and the inner over fold in range(1, 3). Print every (epoch, fold) pair and count the total number of pairs in an accumulator initialized before both loops. Confirm the count is 6, and say in a comment why it is the product of the two ranges rather than their sum.

Then add a guarded break in the inner loop that fires when fold == 2 and epoch == 2. Run it again and print the new count. In a final comment, say exactly which pair is now missing, confirm the outer loop still completed all three epochs, and explain what that tells you about which loop a break ends.


Solution 1: Stop Early, and Skip the Ones You Do Not Want
# Search for the first number divisible by BOTH 6 and 8, then stop.
for n in range(1, 100):
    print("checking", n)
    if n % 6 == 0 and n % 8 == 0:
        print("match", n)
        break     # leave the loop immediately
print("search over")
# 24 numbers were checked, 1 through 24. The loop did not reach 99 because
# 'break' abandons the remaining items the moment the answer is found.

# Skip multiples of 3, and stop entirely once a score passes 15.
for score in range(1, 21):
    if score % 3 == 0:
        continue  # skip THIS score, keep scanning
    if score > 15:
        break     # end the scan altogether
    print("processing", score)
# Processed: 1 2 4 5 7 8 10 11 13 14. The 'continue' removed 3, 6, 9, 12, 15,
# and the 'break' ended the scan at 16, so 17, 19 and 20 were never processed
# even though they are not multiples of 3.

Run it:

# Find the first common multiple, then scan the scores.
python3 scan.py

The first loop reports match 24 after checking twenty-four numbers, 24 being the first number divisible by both 6 and 8.

The second processes 1 2 4 5 7 8 10 11 13 14. The two statements do different jobs on the way there, and the ending is the part worth noticing: the scan stopped at 16 and never looked at 17, 19 or 20, which would all have passed the multiple-of-three filter. A continue costs you one item, a break costs you every item that was left.

DON'T:

  • DON'T reach for break when you mean to skip one item, it ends the loop and every remaining item goes unexamined.
  • DON'T put work after a continue in the same pass expecting it to run, everything below it except a finally block is skipped for that iteration.
Solution 2: Every Pair, and What the Inner break Really Stops
# The accumulator is initialized before BOTH loops, it counts across all passes.
n_pairs = 0
for epoch in range(1, 4):     # outer: 3 passes
    for fold in range(1, 3):  # inner: 2 passes, restarting each outer pass
        n_pairs += 1
        print("epoch", epoch, "fold", fold)
print("pairs:", n_pairs)      # pairs: 6
# It is 3 * 2 and not 3 + 2 because the inner loop runs FULLY on every outer
# pass, so the inner body runs once per combination rather than once per loop.

# Now stop the inner loop early, but only during epoch 2.
n_pairs = 0
for epoch in range(1, 4):
    for fold in range(1, 3):
        if fold == 2 and epoch == 2:
            break             # ends the INNER loop only
        n_pairs += 1
        print("epoch", epoch, "fold", fold)
print("pairs:", n_pairs)      # pairs: 5
# The missing pair is (2, 2). All three epochs still ran, because the break
# ended only the fold loop and handed control back to the epoch loop, which
# carried on to epoch 3. A break leaves one loop, never two.

Run it:

# Print every pair, then repeat with a guarded inner break.
python3 pairing.py

The first nested loop prints all six pairs and the count is 6, the product of the two ranges. The second prints five, and the one that is gone is (2, 2).

The important observation is what did not change. Epoch 3 still ran in full, with both of its folds. The break fired during epoch 2 and ended that epoch's fold loop, and then the outer loop simply took its next pass as though nothing had happened. If you expected the search to be over, this is the moment to correct that expectation, because this lesson's last assessment question and its assignment both turn on it.

DON'T:

  • DON'T expect an inner break to end the outer loop, it ends one level and the outer loop continues.
  • DON'T reuse one name for both iteration variables, the inner loop would overwrite the outer's value and the trace would be meaningless.
  • DON'T initialize the pair counter inside either loop, it accumulates across all passes, so it is initialized before both.

Theory Assessment

Conceptual reinforcement, not a coding section. All four questions with their hints first, then all four answers.

Q1: Leaving Early

Two parts on break. First, explain what break does and where execution goes next, and say what advantage stopping early has over letting a loop finish. Second, explain why a while True: loop is not automatically a bug, and what one thing has to be true for it to be correct.

Hint: break jumps to a specific place, so name it. For the second part, recall the variant from Lesson 1.2.2 and ask what it now moves toward.

Q2: Skipping One, and Why the if Is There

Two parts on continue. First, state the difference between continue and break in one sentence each, and say what happens to the lines below a continue in the same pass. Second, explain why both statements are almost always written inside an if, and what an unguarded continue or break would do to a loop.

Hint: One statement abandons a pass and one abandons the loop. For the second part, ask what happens on the first pass if the statement runs unconditionally.

Q3: Counting and Tracing a Nested Loop

Two parts on nesting. First, if an outer loop runs m times and an inner loop runs n times, say how many times the inner body runs, and why it is that and not m + n. Second, give the exact order of the pairs printed by this loop:

for row in range(2):
    for col in range(3):
        print(row, col)

Hint: The inner loop restarts completely on every outer pass. For the trace, ask which of the two numbers changes fastest, and write all six pairs out in order.

Q4: The Search That Kept Searching

A grid search wants the first pair whose score passes a threshold, then wants to stop. Here is the attempt:

found = None
for lr in [0.1, 0.05]:
    for batch in [16, 32]:
        score = lr * batch
        if score > 1.0:
            found = (lr, batch)
            break
print(found)

The scores are 0.1 * 16 = 1.6, 0.05 * 16 = 0.8 and 0.05 * 32 = 1.6.

Answer three things. First, trace the loop and give the exact value printed, which is not the first passing pair. Second, explain precisely why the wrong pair ends up in found, naming the rule responsible. Third, this bug produced no error and a perfectly reasonable-looking answer, say what would have to be added to make it stop after the first match, and say why a second break placed immediately after the inner loop would work while a break in the inner loop alone does not.

Hint: Write down what found holds after each inner loop finishes, not just at the end. For the third part, ask what the outer loop knows about what the inner loop did, and what would have to be recorded so it could act on it.


Answer 1:

break immediately ends the innermost loop it sits in, abandoning any remaining items or passes, and execution jumps to the first line after that loop once any finally block around the break has run. Stopping early avoids work that cannot change the answer: once you have found the first matching item, every remaining check is wasted, and on a long collection that is the difference between examining a handful of items and examining all of them.

while True: is not automatically a bug, but it is a bug unless one thing holds: there must be a way out inside, such as a break, that is actually reachable. The condition can no longer stop the loop, since it is always true, so the guarded break has taken over the job the condition used to do, and the variant now has to drive that guard true. The pattern is worth having when the real stopping condition is most naturally tested partway through the body rather than at the top.

DON'T write while True: without a reachable way out such as a break, that is a genuine infinite loop with nothing left to stop it.

Answer 2:

continue abandons the rest of the current pass and jumps to the next iteration, and the loop carries on. break abandons the entire loop and execution continues after it. Anything written below a continue, except a finally block, is skipped for that pass, so cleanup or accumulation placed there simply does not happen for the items that were skipped.

Both are almost always guarded by an if because both are unconditional when they are not. An unguarded continue at the top of a body would skip the rest of the body on every single pass, so a for would spin through all its items doing nothing. An unguarded break would end the loop during the first pass, so the body would run at most once. In each case the guard is what turns "always" into "when this particular item calls for it".

DON'T put essential work below a continue outside a finally block, it is skipped for exactly the items the continue was meant to filter.

Answer 3:

The inner body runs m * n times. It is a product rather than a sum because the inner loop runs to completion on every outer pass, so its n passes happen once per outer pass rather than once in total. Adding them would describe two loops one after the other, not one inside the other.

The pairs come out in this order: 0 0, 0 1, 0 2, 1 0, 1 1, 1 2. The second number changes fastest and cycles through all its values before the first number moves at all, which is the visible signature of nesting and the quickest way to check you have the loops the right way round.

DON'T reuse the same iteration variable for both loops, the inner one would overwrite the outer's value mid-pass.

Answer 4:

It prints (0.05, 32). Trace it by watching found after each inner loop ends. With lr = 0.1, the first batch gives 1.6, which passes, so found becomes (0.1, 16) and the inner loop breaks. The outer loop then takes its next pass. With lr = 0.05, batch 16 gives 0.8 and fails, then batch 32 gives 1.6 and passes, so found is overwritten with (0.05, 32). That is the value printed.

The rule responsible is that break ends only the innermost loop it sits in. It ended the batch loop, handed control back to the learning-rate loop, and that loop had no idea a match had been found, so it carried on searching and found another one. The code says "stop looking" only to the inner loop, and the outer loop was never told.

To stop after the first match the outer loop needs to know something happened, which means recording it and acting on it. Since found is already set on a match, a second break placed immediately after the inner loop, guarded by if found is not None:, ends the outer loop too. That works because the two break statements sit in different loops, so between them they leave both levels, whereas the inner break alone can only ever leave one. With break, the general shape is that leaving k nested loops takes k exits, or a flag that each level checks.

DON'T trust that an inner break ended a search, and DON'T take a plausible answer as evidence that it did. This version raised nothing, ran quickly, and returned a real pair that genuinely passes the threshold, it is simply not the one that was asked for.


Assignment

One assignment. The problem and its hints first, then the solution.

Assignment: Grid Search with Early Exit

Create grid_search.py, simulating a hyperparameter search. Nest a loop over lr in [0.1, 0.05, 0.01] as the outer and batch in [16, 32, 64] as the inner. For each pair compute a fake score = lr * batch, print the pair with its score, and count the trials actually run in an accumulator.

Use continue in the inner loop to skip any pair where batch == 32, simulating a disallowed configuration. Use break in the inner loop to stop trying batches for the current lr as soon as a score > 3.0 is found, moving on to the next lr. Attach a for-else to the inner loop that prints "all batches tried" only for those learning rates whose inner loop finished without breaking. After everything, print the total number of trials run.

In comments, settle three things: how many trials ran for each lr and why, why the inner break does not end the outer search, and why the skipped batch == 32 pairs are not counted as trials even though the loop visited them.

Hints:

  • The inner break ends only the batch loop, so the outer loop simply moves to the next learning rate and the search continues. That is the behavior being relied on here, not worked around.
  • Put the continue guard before the score is computed, and remember the for-else runs only on inner loops that finished without breaking, so it will not fire for a learning rate that broke out early.

Solution:
n_trials = 0
for lr in [0.1, 0.05, 0.01]:
    for batch in [16, 32, 64]:
        if batch == 32:
            continue              # disallowed config, not a trial
        score = lr * batch
        n_trials += 1             # counted only for configs we ran
        print("lr", lr, "batch", batch, "score", round(score, 4))
        if score > 3.0:
            print("  good enough, next lr")
            break                 # ends the BATCH loop only
    else:
        # for-else: runs only when the inner loop finished without a break.
        print("  all batches tried")
print("total trials:", n_trials)  # total trials: 6
# Trials per lr: 0.1 ran 2 (batch 16 scored 1.6, batch 64 scored 6.4 and broke),
# 0.05 ran 2 (0.8, then 3.2 and broke), 0.01 ran 2 (0.16 and 0.64, no break),
# so only 0.01 reaches the for-else and prints all batches tried.
# The inner break does not end the outer search because break leaves exactly one
# loop, the innermost it sits in, and control returns to the lr loop.
# The batch == 32 pairs are visited but 'continue' fires before n_trials += 1,
# so they are skipped rather than counted, which is the difference between the
# loop touching an item and the program doing work on it.

Run it:

# Run the grid search with a skip rule and an early exit.
python3 grid_search.py

Six trials run in total, two for each learning rate, and only 0.01 reaches the for-else and prints all batches tried.

Two things here are worth separating, because they look similar and are not. The continue on batch == 32 means that configuration is never a trial at all, the loop visits it and the program declines to do anything with it, which is why n_trials stops at six rather than nine. The break on a good score means the remaining batches for that one learning rate are abandoned, but the search itself carries on, which is exactly what a per-lr early exit should do.

The for-else is what makes the distinction visible from the outside. It fires only for 0.01, the one learning rate that never found a good enough score, so its absence for 0.1 and 0.05 is the report that those two ended on a break. Without it, a learning rate that broke out and one that simply ran out of batches leave the inner loop the same way, and the outer loop could tell them apart only by checking something recorded inside it, a flag set before the break, the way Question 4's fix checks found.

DON'T expect the inner break to end the whole search, it ends one level and the outer loop takes its next pass. And DON'T count a skipped configuration as a trial, put the continue above the counter so that visiting an item and running it stay distinct.


Additional Resources

Optional, and nothing that follows depends on either one. Worth opening only if this lesson left a question behind.

  • YouTube - "Learn Python - Full Course for Beginners [Tutorial]" by freeCodeCamp.org. The "2D Lists & Nested Loops" chapter, for a second visual pass over nested loops.
  • Official docs - Python Language Reference, "The break statement" and "The continue statement". Exactly where each one is legal to write and what it binds to.

Summary

This lesson handed you the fine controls that turn a loop from a blunt "do this for everything" into a precise instrument. break lets a loop quit the instant its job is done, the first match found, the threshold crossed, the answer in hand, so it stops wasting passes on work that no longer matters. continue lets a loop step over the items it should ignore, the missing values, the rows that fail a filter, without burying the real work under another layer of indentation. Neither is useful on its own: each is almost always the verb at the end of an if, firing only when the condition that justifies it is met. The loop runs normally until something special happens, and then one of these statements changes the flow.

Nesting is the larger leap. Putting one loop inside another is how a program reaches into two dimensions at once, every combination of two collections, every cell of a grid, every pairing of one thing with another. The cost is that you must now hold two counters in your head at the same time, and trace the inner loop running over and over, restarting on each outer pass that reaches it. The discipline this builds, reading execution order carefully, knowing that the inner loop finishes before the outer advances, remembering that break and continue touch only the innermost loop, is exactly the discipline that complex code demands everywhere.

The data work ahead leans on all of this constantly. Scanning a table for the first row that matches a rule and stopping there is a break. Walking every row while skipping the dirty ones is a continue. Comparing every record against every other, or sweeping a grid of hyperparameter settings, is a nested loop. With this lesson the section's promise is fulfilled: you can make a program choose between paths, repeat work in two different loop styles, accumulate a running result, reason about why a loop stops, and now steer that repetition precisely. Choosing and repeating are what turn a calculator into an algorithm, and this section has given you both.


Cheat Sheet

Part A - Reference Table

Concept Syntax Effect When to avoid
break if cond: break Exits the innermost loop at once, after any finally Needing to exit multiple loops at once
continue if cond: continue Skips rest of this pass, loop continues When you actually need to stop (use break)
while True + break while True: ... break Loop forever until break fires No reachable way out, such as a break (infinite loop)
Nested loop loop inside a loop Inner runs fully on each outer pass that reaches it, m*n if none skips or breaks it Reusing the same loop variable name
Inner break break in inner loop Ends inner loop only, outer continues Expecting it to exit the outer loop
for/else for ...: ... else: else runs only on normal completion, never after a break Expecting else after a break

Part B - Compact Code Block

for n in range(100):    # find first match, then stop
    if n > 50:
        break           # exits the loop immediately

for char in "loss":     # skip bad items, keep looping
    if char == "o":
        continue        # jump to next pass
    print(char)

for i in range(3):      # nested loop: inner runs fully per outer pass
    for j in range(2):  # j restarts each outer pass
        print(i, j)     # runs 3 * 2 = 6 times

for n in range(100):    # search-else-not-found pattern
    if n == target:
        break
else:
    print("no match")   # runs only if loop never broke
←Previous: Lesson 3
Next: Section 3, Functions→

Questions about this lesson: #module-1 on Discord

Found an error in this lesson? Report it

Your progress
Current streak
🔥 0
Lessons marked today
0 / 3
Longest streak
0

Sign in

The bootcamp

  • Curriculum
  • How To
  • Pricing
  • Changelog
  • Future

The community

  • Discord
  • Reviews
  • Contact

Follow

  • Instagram
  • X
  • TikTok
  • Reddit

Legal

  • Terms
  • Privacy
  • Refunds

Coming soon on November 16, 2026

Theme