Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 07 / VALUES AND CONTROL FLOW

Loops without off-by-one surprises

Repeat useful work, accumulate results and know when to stop.

FoundationTutorial 12 min core+8 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 12 minutes; optional deep dive: 8 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Iterate values with for
  • Use range and enumerate
  • Build terminating while loops
01

Iterate values before indexes

A for loop visits values from an iterable. An accumulator keeps a result built across those visits.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Totals and numbered reports need repeated work. Reading the values directly avoids unnecessary index arithmetic.

Words you will see

Iterable
Something from which a loop can obtain values, such as a list or range.
Accumulator
A result updated as items are visited.
enumerate
An operation producing pairs of a counter and each source value.

Initialise once, update for every value

total starts at zero before the loop. The values 3, 5 and 2 update it to 3, then 8, then 10. total += value means adding the current value and rebinding total. It does not reset the running sum.

The second loop uses enumerate with start=1. Each pair is unpacked into position and item, giving 1 tea and 2 rice. This counter is a display number, not a claim that list indexes now start at one. Use enumerate when you need both numbering and the actual value.

Choose values, counters or positions

Use for item in items when only values matter. Use range(stop) for a known count; it yields integers starting at zero and excluding stop, without allocating a list of them all. Use an actual index when you must access a specific neighbor or slot.

An empty list runs the body zero times, leaving a correctly placed initial total at zero. Initialising total inside the body would repeatedly erase earlier work. sum is a useful alternative for a straightforward numeric total, but writing this loop makes the changing state visible.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. total = 0

    Create the neutral starting sum once.

  2. for value in [3, 5, 2]:

    Visit three source values in order.

  3. total += value

    Accumulate 3, then 8, then 10.

  4. print(total)

    Print after all additions.

  5. for position, item in enumerate(["tea", "rice"], start=1):

    Pair display numbers 1 and 2 with the two items.

Use for item in items when you need each value. Use enumerate when you also need a position. range(stop) excludes stop and avoids allocating a list of all integers.

Conceptual accumulator states for the original values

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Initial statetotal is 0 before any visits.
  2. Update ruleEach visit adds its value to the previous total.
  3. Completed state0 + 3 + 5 + 2 is 10; print happens after the loop.
Predict before you run

What intermediate totals lead to the first output?

A running totalPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Add one visit.

Try: Append 4 to the numeric list.

The total becomes 14; the separate numbered report is unchanged.

Use zero-based display numbers.

Try: Change start=1 to start=0.

The report starts with 0 tea; the source list itself is unchanged.

Before you move on

If the list in the sum loop is empty, what total prints and why?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

Zero prints. The initial binding happens before the loop, and no visits occur to change it.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Use while for a changing condition

A while loop repeats as long as its condition is truthy. Its body must make progress toward a stopping condition when termination is required.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Some processes stop because state changes, not because a fixed list has ended. A small countdown makes the progress rule explicit.

Words you will see

Loop condition
The question checked before every attempted iteration.
State
Values that determine what the next iteration will do.
Termination
The loop finishing rather than repeating forever.

Check, act, progress, check again

remaining starts at 3. The condition remaining > 0 succeeds, so the body prints 3 and subtracts one. The next visits print 2 and 1. After the decrement to zero, the next condition fails and execution continues to print done.

The condition is checked before the body, so an initial zero runs no countdown visits. Indentation matters: the decrement belongs inside the loop. If it were outside, remaining would stay at 3 throughout the loop and the program would not reach it.

Pick the simpler repetition rule

For a fixed count, for number in range(3, 0, -1) expresses the same countdown without manual state updates. Use while when a changing condition is the central rule, such as retrying while attempts remain and no valid result has arrived.

A visible progress measure helps you reason about termination. Here it is a nonnegative integer decreasing by one. A real retry also needs a finite attempt budget and an error policy. Do not rely on pressing Stop as the program's intended termination strategy.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. remaining = 3

    Supply the starting state.

  2. while remaining > 0:

    Check before every iteration, including the first.

  3. remaining -= 1

    Make progress after printing the current count.

  4. print("done")

    Run after the condition becomes False.

A while loop repeats while its condition is truthy. Make the state change toward termination visible. For a known number of repetitions, range is usually simpler.

Predict before you run

Does the body print zero?

A countdown with visible progressPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Start already finished.

Try: Change remaining = 3 to remaining = 0.

Only done prints.

Include zero deliberately.

Try: Change the condition to remaining >= 0.

The countdown also prints 0, then decrements to -1 and stops.

Before you move on

If remaining starts at 1, how many times does the body run?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

Once. It prints 1, decrements to zero and fails the next condition check. done then prints.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Break and continue have different jobs

continue skips the rest of the current iteration. break leaves the nearest loop entirely.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A stream may contain values to ignore and a marker that means stop. Treating those cases the same loses later valid data or reads too far.

Words you will see

Iteration
One visit through a loop body.
continue
Move to the next iteration, rechecking a while condition if needed.
break
Exit the nearest enclosing loop.

Ignore and stop are different decisions

The list contains 2, 0, 3, -1 and 8. Zero reaches continue, so no addition happens for that visit. The next value 3 still runs normally. A negative value reaches break, ending the loop before 8 is visited.

The total is 5 from 2 and 3. Moving total += value above the tests would add values before deciding whether to ignore or stop. Replacing break with continue would let 8 contribute, changing the result to 13.

Keep traversal and editing separate

This loop only reads the source list and changes a separate integer total. Removing elements from the same list while traversing it can shift positions and skip values. Build a filtered result or deliberately traverse a snapshot instead.

Use a simple if around the useful work when that is clearer than continue. Use a function return for a search that should immediately supply a found result to its caller. In nested loops, break exits only the nearest loop, not every enclosing loop.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. if value == 0:

    Identify visits that contribute nothing.

  2. continue

    Skip the remaining body but keep visiting later values.

  3. if value < 0:

    Identify the end marker.

  4. break

    Stop before reaching 8.

  5. total += value

    Add only the accepted values 2 and 3.

break exits the nearest loop; continue skips to its next iteration. Repeatedly removing items from the same list you are traversing can skip elements. Build a filtered result or iterate a copy instead.

Predict before you run

Does 8 contribute to the sample total?

Skip zero, stop at a negativePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Change stopping into skipping.

Try: Replace break with continue.

The total becomes 13 because 8 is now visited and added.

Move the marker.

Try: Change the source to [-1, 2, 3].

The total stays zero; the first visit stops immediately.

Before you move on

For [4, -1, 6], what total would this rule produce?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

It produces 4. The negative marker stops traversal before 6; the marker itself is not added.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

A loop expresses repeated work under an ordering and termination contract. Processing a sequence of values, searching until a match and retrying an external operation are different problems even if all use repetition. Identify what state changes, what output accumulates and what proves the work will finish before choosing for or while.

Follow the mechanism step by step

A for loop requests values from an iterator until it is exhausted. range is a compact iterable of integers rather than a prebuilt list. A while loop re-evaluates a condition, so its body must move relevant state toward termination or intentionally wait under a bounded policy. break exits the nearest loop; continue skips the remaining current body.

Work through a concrete application

Trace a running total with a table showing the current value and total before and after each iteration. For a search, decide whether to return the first match, all matches or a missing-value marker. Use enumerate when the position matters and zip when paired inputs have a deliberate length policy; silently truncating mismatched streams may be a bug.

Failure cases and misleading shortcuts

Changing a list's length while traversing it can move values past the iterator's next position. A continue placed before a while-loop counter update can create nontermination. Broad exception handlers can also turn a failure into an infinite retry. Keep mutation and progress visible instead of hiding them in a complex condition.

Cost, ownership and alternatives

Count the work done inside the body. One traversal with constant-cost updates is O(n), but a repeated scan or list membership test can introduce quadratic work. Accumulating all intermediate results changes memory usage; a running total needs only bounded extra state when numeric sizes are bounded.

Verify the contract

Test empty input, one item, a match at each end, no match and repeated values. For while loops, test the boundary where the initial condition is false and where the limit is reached exactly. Use a bounded iteration count or explicit deadline for externally driven loops rather than relying on a test eventually completing.

Transfer question: Why can zip silently lose records in an import task?

Normal zip stops at the shortest iterable, so extra records from a longer input are never paired. If equal lengths are required, validate them or use strict zip on a supported Python version and handle the mismatch explicitly. If truncation is intentional, document it as part of the task.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Which values does range(3) produce?
What does continue do?
TRANSFER THE IDEA

Sum positive values

Accumulate only positive values. Zero contributes nothing.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Guided: sum positive entries

Accumulate only values strictly above zero.

The contract

  • values is a list of integers, including zeros and negatives.
  • Return the integer sum of strictly positive entries. Keep repeated entries as repeated contributions.
  • Empty input or no positive entries returns 0. Preserve the list and its order.
Guided: sum positive entriesPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. mixed values
    from copy import deepcopy
    args = ([-2, 4, 0, 7],)
    before = deepcopy(args)
    expected = 11
    result = positive_total(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for mixed values"
    assert args == before, "Preserve every supplied input"
  2. empty source
    from copy import deepcopy
    args = ([],)
    before = deepcopy(args)
    expected = 0
    result = positive_total(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty source"
    assert args == before, "Preserve every supplied input"
  3. all negative
    from copy import deepcopy
    args = ([-3, -1],)
    before = deepcopy(args)
    expected = 0
    result = positive_total(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for all negative"
    assert args == before, "Preserve every supplied input"
  4. zero only
    from copy import deepcopy
    args = ([0, 0],)
    before = deepcopy(args)
    expected = 0
    result = positive_total(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for zero only"
    assert args == before, "Preserve every supplied input"
  5. repeat positives
    from copy import deepcopy
    args = ([3, 3, -1],)
    before = deepcopy(args)
    expected = 6
    result = positive_total(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for repeat positives"
    assert args == before, "Preserve every supplied input"
  6. single positive
    from copy import deepcopy
    args = ([8],)
    before = deepcopy(args)
    expected = 8
    result = positive_total(*args)
    assert type(result) is type(expected) and result == expected, "Return the exact value and type for single positive"
    assert args == before, "Preserve every supplied input"
    Why not return at the first positive value?

    It would ignore later contributions. One pass takes O(n) visits and only a running sum as auxiliary state, apart from the size of the integer itself.

    GUIDED PRACTICE

    Guided: number the source order

    Produce one numbered display string for every item.

    The contract

    • items is a list of strings.
    • Return a new list with exact strings '1: ITEM', '2: ITEM' and so on, numbering from one.
    • Keep empty strings, duplicates and input order. Empty input returns []; never mutate items.
    Guided: number the source orderPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. two labels
      from copy import deepcopy
      args = (["tea", "rice"],)
      before = deepcopy(args)
      expected = ["1: tea", "2: rice"]
      result = numbered_labels(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for two labels"
      assert args == before, "Preserve every supplied input"
      assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
    2. empty list
      from copy import deepcopy
      args = ([],)
      before = deepcopy(args)
      expected = []
      result = numbered_labels(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty list"
      assert args == before, "Preserve every supplied input"
      assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
    3. single label
      from copy import deepcopy
      args = (["x"],)
      before = deepcopy(args)
      expected = ["1: x"]
      result = numbered_labels(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for single label"
      assert args == before, "Preserve every supplied input"
      assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
    4. duplicates
      from copy import deepcopy
      args = (["a", "a"],)
      before = deepcopy(args)
      expected = ["1: a", "2: a"]
      result = numbered_labels(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for duplicates"
      assert args == before, "Preserve every supplied input"
      assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
    5. empty label
      from copy import deepcopy
      args = ([""],)
      before = deepcopy(args)
      expected = ["1: "]
      result = numbered_labels(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty label"
      assert args == before, "Preserve every supplied input"
      assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
    6. keep whitespace
      from copy import deepcopy
      args = ([" z ", "a"],)
      before = deepcopy(args)
      expected = ["1:  z ", "2: a"]
      result = numbered_labels(*args)
      assert type(result) is type(expected) and result == expected, "Return the exact value and type for keep whitespace"
      assert args == before, "Preserve every supplied input"
      assert result is not args[0] and all(type(label) is str for label in result), "Respect nested types and ownership promises"
      Why not sort before numbering?

      The contract asks for original order, not alphabetic order. Work and output storage grow with the number and length of the produced labels.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: stop reading at a marker

      A negative value now ends processing; it is not merely ignored.

      The contract

      • values is a list of integers.
      • Return the integer sum of all values before the first negative value. Exclude that marker and every later value.
      • Zero is allowed and does not stop the loop. Empty input returns 0. Do not mutate or sort the list.
      Transfer: stop reading at a markerPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. middle marker
        from copy import deepcopy
        args = ([2, 0, 3, -1, 8],)
        before = deepcopy(args)
        expected = 5
        result = total_before_marker(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for middle marker"
        assert args == before, "Preserve every supplied input"
      2. empty input
        from copy import deepcopy
        args = ([],)
        before = deepcopy(args)
        expected = 0
        result = total_before_marker(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty input"
        assert args == before, "Preserve every supplied input"
      3. first marker
        from copy import deepcopy
        args = ([-1, 8],)
        before = deepcopy(args)
        expected = 0
        result = total_before_marker(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for first marker"
        assert args == before, "Preserve every supplied input"
      4. no marker
        from copy import deepcopy
        args = ([2, 3, 4],)
        before = deepcopy(args)
        expected = 9
        result = total_before_marker(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for no marker"
        assert args == before, "Preserve every supplied input"
      5. zero is data
        from copy import deepcopy
        args = ([0, 4, -2, 9],)
        before = deepcopy(args)
        expected = 4
        result = total_before_marker(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for zero is data"
        assert args == before, "Preserve every supplied input"
      6. repeated entries
        from copy import deepcopy
        args = ([3, 3, -1, 3],)
        before = deepcopy(args)
        expected = 6
        result = total_before_marker(*args)
        assert type(result) is type(expected) and result == expected, "Return the exact value and type for repeated entries"
        assert args == before, "Preserve every supplied input"
        Why does the previous positive_total fail this requirement?

        It keeps scanning after negatives and would add later positive entries. This version visits at most n entries and can stop earlier; it keeps only one running integer.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Reason about work, not syntax

        Loop cost depends on how many times the body runs and what each visit does, not on how many loops are visible in source.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A short nested loop can repeat work many times. A nested loop with a fixed small inner range can instead grow only linearly with input size.

        Words you will see

        n
        The number of source items in this analysis.
        O(n)
        A growth bound proportional to n, ignoring fixed factors under the stated assumptions.
        O(n²)
        A growth bound proportional to the square of n.

        Count visits before naming the growth

        The first nested loop visits all three values for each of the three outer visits, so pairs becomes 9. For n values it visits n times n pairs. The second loop repeats a fixed range(2) for each value, so fixed becomes 6; for n values that is 2n visits.

        Both examples have nested syntax, but only the first has two input-sized bounds. The variables left, right and item are not otherwise used because the sample counts work rather than calculating a product. range excludes its stop, so range(2) gives exactly two visits.

        State assumptions and output needs

        Under a bounded-cost increment assumption, the first pattern is O(n²) and the second O(n). Arbitrarily large Python integers make exact per-increment cost more subtle. These examples store only counters, not a list of every pair.

        If you actually build every pair as output, the result itself has n² entries and requires corresponding storage. An algorithm cannot promise linear output storage while returning a fully materialised quadratic-size list. Measure real workloads separately; these counts do not claim a duration in milliseconds.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. for left in values:

          Begin three outer visits.

        2. for right in values:

          Repeat three inner visits for each outer visit.

        3. pairs += 1

          Count all nine pairs without storing them.

        4. for repeat in range(2):

          Use a fixed two-visit inner bound for the second count.

        5. print(pairs, fixed)

          Compare nine input-pair visits with six fixed-inner visits.

        One pass through n items is O(n) if each body operation has bounded cost. A nested scan can be O(n squared), but nesting alone is not proof: inspect the bounds and the cost of each operation.

        Predict before you run

        Why is the second count 6, not 9?

        Count the inner visitsPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Grow the input once.

        Try: Add 8 to values.

        The output becomes 16 8: the two growth patterns separate further.

        Change only a fixed factor.

        Try: Change range(2) to range(3).

        The second count becomes 9 for this input, but its growth with n remains linear.

        Before you move on

        For four source items and an inner range(2), how many fixed-loop visits occur? How many all-pairs visits?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        There are 8 fixed-loop visits and 16 all-pairs visits. Doubling a fixed factor differs from multiplying by the input length again.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Loop else means no break

        A loop's else block runs when the loop finishes without break. It does not mean that the final condition was false in the same way as an if/else.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A search needs a result for the not-found case, including an empty source. Loop else can express that without a separate found flag.

        Words you will see

        Exhaustion
        A for loop reaching the end of its iterable.
        Search
        Visiting candidates until one meets a requirement.
        Loop else
        A block entered on normal loop completion, but not after break.

        Read the stopping reason

        The sample visits tea and rice while looking for bread. Neither comparison succeeds, so no break executes. The loop exhausts its source, then the else block prints not found. The else is aligned with for, not the inner if.

        If a candidate matches, found prints and break skips the else block. An empty source also has no break, so else still prints not found. continue alone does not suppress else because it does not end the loop by breaking.

        Choose a form the reader can follow

        For a small local search, loop else avoids maintaining a separate flag. A helper function that returns as soon as it finds a match and returns a fallback after the loop is often clearer, especially when the result is reused.

        The else block is not guaranteed after every possible loop exit. A return or exception also prevents normal fall-through to it. Do not put mandatory cleanup here; use a finally block or resource-management construct when cleanup must occur despite errors.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. wanted = "bread"

          Choose a value absent from the source.

        2. if item == wanted:

          Test each candidate; both comparisons fail.

        3. break

          This would skip else if a match were found, but it is never executed here.

        4. print("not found")

          Run after the iterable is exhausted without break.

        A for/while else clause runs when the loop finishes without break, including an empty for loop. It can express unsuccessful search, but a small function returning a found result is often easier to explain.

        Predict before you run

        Why does not found print once rather than twice?

        A search that never breaksPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Find a candidate.

        Try: Change wanted to "rice".

        found prints and break suppresses the else block.

        Search no candidates.

        Try: Replace ["tea", "rice"] with [].

        not found still prints once.

        Before you move on

        What happens if the source is [] with the same loop else?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        The body has no visits and no break, so the else block prints not found. Empty input is normal unsuccessful search.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.