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 59 / SCENARIO-BASED QUESTIONS

Scenario: one bad item hides the rest of a batch

A batch job catches Exception around the whole loop and returns an empty success report after one malformed item. Valid earlier results disappear, later items are not attempted, and operations staff cannot identify which record failed.

IntermediateScenario 18 min core+12 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 who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 18 minutes; optional deep dive: 12 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
  • Build a diagnosis from evidence
  • Compare a repair with its trade-offs
  • Test the changed behaviour
DIAGNOSTIC CASE FILE

Follow the evidence.

A batch job catches Exception around the whole loop and returns an empty success report after one malformed item. Valid earlier results disappear, later items are not attempted, and operations staff cannot identify which record failed.

Observed evidence

  • The catch surrounds the entire batch rather than one declared failure boundary.
  • The response does not distinguish failure from a valid empty result.
  • There is no stable record identifier attached to errors.

Investigation sequence

  1. Decide whether the contract is all-or-nothing or partial results.
  2. Identify expected item-validation failures separately from infrastructure/programming errors.
  3. Return structured successes and bounded per-record errors only if partial processing is allowed.

Challenge the repair

  • Add a regression case in which the first, middle and last records are invalid.
  • How would the design change if each record triggered an external payment?
01

Read the incident, not just the error

A partial batch contract keeps successful independent items and reports declared item failures. It differs from a contract that rejects the whole batch.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The incident hides earlier valid values and never tries later ones after one conversion fails. Decide whether partial processing is allowed before moving an exception handler.

Words you will see

Batch
A group of items processed under one declared contract.
Partial result
A report containing both successes and item failures.
Failure boundary
The operation whose expected failures a handler is allowed to recover from.

Reproduce the lost later item

The outside try in the model surrounds the entire loop. int('bad') raises ValueError and control jumps to except. The later '3' is never visited. Earlier value 2 survives in this diagnostic list, but a handler that returns [] would hide it too.

Put a valid item before and after the bad one. That input distinguishes continuing per item from stopping the batch. An all-valid test cannot reveal the handler-placement bug. An empty list alone cannot distinguish valid emptiness from hidden failure.

Choose the business promise first

Independent imports may permit partial results; a balanced financial posting may require atomic rejection. Moving the catch inside the loop changes the promise if later items depend on earlier ones. External writes need transaction or reconciliation design beyond this parser.

The reproduction stores at most n converted integers for n input texts and scans until the first failure. Do not describe that short scan as an optimization: it is missing required work under a partial contract. The repair needs separate ordered successes and failures.

The original example, step by step

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

  1. values = []

    Start an observable diagnostic list.

  2. for text in ['2', 'bad', '3']:

    Put good data on both sides of the bad input.

  3. values.append(int(text))

    Convert before appending; the second conversion raises.

  4. except ValueError:

    Handle outside the loop, so the loop is not resumed.

  5. print(values)

    Only the earlier 2 survived.

A batch job catches Exception around the whole loop and returns an empty success report after one malformed item. Valid earlier results disappear, later items are not attempted, and operations staff cannot identify which record failed.

Conceptual exception-boundary change

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

  1. OutsideOne failure exits the entire loop.
  2. DecideConfirm that items are independent and partial results are allowed.
  3. InsideHandle only expected conversion failure, record its key, then continue.
Predict before you run

Does the final list contain 3?

Reproduce an outside-loop catchPYTHON 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.

Move the invalid text first.

Try: Use ['bad', '2', '3'].

The diagnostic list is empty because no successful conversion precedes failure.

Remove the malformed text.

Try: Use ['2', '3'].

Both values appear, showing why all-valid tests miss the boundary defect.

Before you move on

If 'bad' is the first item, will this loop still attempt the following valid item?

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

No. The exception exits the loop to the outside handler. Per-item recovery requires a handler inside the loop and a contract that permits continuing.

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

Investigate before changing code

A useful batch report identifies which items succeeded and which failed, without pretending that an invalid item was a successful empty result.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Operators need a stable record key to reconcile partial work. A result list without failure identifiers cannot tell callers which items require correction.

Words you will see

Stable identifier
A label retained across attempts so an item can be recognized.
Expected failure
A declared input problem that the function is designed to report.
Reconciliation
Matching reported outcomes to the submitted items.

Separate categories without losing order

The model explicitly records one success and one failed key. Successes are key/value pairs; errors are keys rather than raw personal records. Separate lists can preserve relative order within each category while representing repeated IDs as repeated occurrences.

The sum of success and failure counts equals attempted items only if every attempted item enters exactly one category. A programming error must not be relabeled as ordinary bad input. Define accepted record shape before applying this accounting rule.

Keep validation narrow and visible

int accepts whitespace and signs for string inputs; it is not a rule that a domain quantity must be nonnegative. Catch ValueError for malformed integer text. Unsupported shape or a TypeError should propagate under this lesson's string-input contract.

For n input records, retaining all successes and failed keys needs O(n) output space apart from the sizes of integers and text. If failures are huge, cap error samples separately from the total failure count; otherwise reporting can become the next memory incident.

The original example, step by step

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

  1. values = [('a', 2)]

    Represent a successful value together with its source key.

  2. errors = ['b']

    Keep the failed item's key separately.

  3. attempted = 2

    State the number of classified occurrences.

  4. print(len(values) + len(errors) == attempted)

    Check that the two categories account for both occurrences.

Decide whether the contract is all-or-nothing or partial results. Identify expected item-validation failures separately from infrastructure/programming errors. Return structured successes and bounded per-record errors only if partial processing is allowed.

Predict before you run

Does this report account for both attempted occurrences?

Reconcile a structured reportPYTHON 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.

Reveal missing classification.

Try: Change attempted to 3.

The accounting check becomes False, exposing a missing outcome.

Retain repeated failed keys.

Try: Use errors = ['b', 'b'] and attempted = 3.

The check is True because each failed occurrence counts separately.

Before you move on

Two occurrences share key x; one parses and one fails. Should a set of keys replace these lists?

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

No under an occurrence-preserving contract. A set loses multiplicity and may hide that the same key had different outcomes. Keep ordered entries or introduce explicit occurrence identifiers.

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

A repair you can explain

Place the handler around one integer conversion when malformed text is the declared recoverable item error. Continue with later records and return both categories.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The preserved original shows a small partial parser with no external effects. It is appropriate when each (key, text) record is independent and text is a string.

Words you will see

ValueError
An exception for a value that the requested operation cannot accept.
else on try
A block run when the try block completes without raising.
Unwinding
Leaving the current operation to find a matching handler.

Read the actual conversion boundary

Each loop iteration unpacks key and text. Only int(text) is in try. A malformed integer appends its key to errors. Otherwise else appends the successful pair. The next iteration happens after either path, so c is still processed after b fails.

Neither list changes the supplied records. Output lists are newly allocated; their tuple entries contain strings and integers. Duplicate keys remain duplicate occurrences. Empty records returns two empty lists, which is an honest empty batch rather than a failure fallback.

Do not promise more than this source does

The parser permits signed integers and does not catch TypeError for non-string unsupported values. It does not transact database writes, retry a failed payment or redact a production logging pipeline. Those are different contracts, not implied by this green sample.

For n records the loop attempts n conversions. Conversion cost depends on each text's length and integer size, so O(n) describes loop iterations rather than a universal byte-level cost. The two lists retain at most n outcome entries altogether.

The original example, step by step

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

  1. values, errors = [], []

    Allocate separate result lists for this call.

  2. value = int(text)

    Attempt the one declared conversion.

  3. errors.append(key)

    Retain only the failed item's identifier.

  4. values.append((key, value))

    Store successful values with their identifiers.

  5. return values, errors

    Return an ordered pair of independently inspectable categories.

Only the expected conversion failure is handled per item. The report distinguishes successful values from failed keys rather than returning a success-shaped empty fallback.

Predict before you run

Which successful keys survive the malformed middle item?

Make partial results explicitPYTHON 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.

Test genuine emptiness.

Try: Call parse_batch([]).

The result is ([], []), with no failures or attempted items.

Test narrow error handling.

Try: Call parse_batch([('x', None)]).

TypeError propagates because this lesson does not declare unsupported non-string values recoverable.

Before you move on

What does this source do with [('x', '-2'), ('x', 'bad')]?

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 returns ([('x', -2)], ['x']). Negative integers are allowed and repeated IDs are not collapsed. A nonnegative domain rule would need an explicit additional requirement.

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

Reproduce the misleading empty success

Place valid records before and after a malformed record and run the original batch handler. The outside catch unwinds the entire loop on the bad item, discards evidence of earlier work, and prevents later work from being attempted. An empty returned collection is ambiguous because it also represents a genuinely empty successful batch. Preserve a failing expectation that identifies the successful records and the failing key rather than checking only that no exception escaped.

Decide the business contract before moving the catch. Some batches are all-or-nothing, while others permit independent successes. Neither policy is universally superior. Ask whether later records depend on earlier ones, whether any external effects already occurred, and whether callers can reconcile partial outcomes. Without those answers, changing to per-item handling can accidentally convert an atomic operation into a partially committed one or repeat side effects after an ambiguous failure.

Locate the narrow expected failure boundary

The reference parse_batch handles ValueError from converting each text value to an integer. It returns successful key-value pairs separately from failed keys, so a, b, and c produce successes for a and c and an error for b. The try block covers conversion rather than the entire batch. Other defects still propagate instead of being mislabeled as user validation, preserving evidence that a programming or infrastructure problem needs a different response.

Integer conversion does not enforce every domain rule. Negative values are accepted by this particular parser, so do not claim that it validates study-minute constraints without adding that requirement. A TypeError from an unsupported input shape is not automatically an expected conversion error either. Define record shape, duplicate-key policy, and value constraints at an explicit boundary, then attach stable identifiers and safe reasons to declared item failures without exposing full sensitive payloads.

Repair reporting and side-effect ownership together

For permitted partial parsing, accumulate successes and structured errors and maintain input-relative order within each output if that is the contract. Include attempted, succeeded, and failed counts so an operator can reconcile the batch. Cap error samples and provide a separate count of omitted details. An unbounded list of bad records can become a memory failure even when successful values are streamed, and raw record retention can create unnecessary privacy risk.

For all-or-nothing database work, validate before applying effects or use an appropriate transaction boundary. External effects need idempotency and recovery beyond an in-memory parser. A report that says an item failed because its acknowledgment was lost may describe an uncertain outcome rather than a definite non-application. Represent that state explicitly where relevant. Retrying only failed identifiers is safe only when the failure classification and effect identity make that retry meaningful.

Verify every position and the meaning of completion

Test invalid first, middle, and last records, all-invalid input, empty input, repeated identifiers, and valid zero values. Assert that records after an expected validation failure are attempted under a partial policy. Inject an unexpected exception and confirm it is not converted into a normal validation report. Verify counts reconcile with the declared attempts, and check ordering so a refactor to concurrency cannot silently rearrange results that callers rely on.

The parser fixture has no database, network call, or durable acknowledgment, so it cannot prove rollback or exactly-once processing. Build separate integration tests for those adapters using isolated state. Exercise failure after an effect but before its acknowledgment, and verify that the report does not call the whole batch complete. Partial reporting is a data contract that requires callers to act on failures; it is not a universal exception-swallowing strategy for keeping dashboards green.

Transfer question: Each parsed record now triggers a payment. Can the existing successes-and-errors lists safely drive automatic retries?

Only after the payment boundary distinguishes definite rejection from uncertain completion. Give every intended payment a stable identity tied to its payload and recover the authoritative outcome when a response is lost. A timeout cannot be put into a simple failed list and blindly replayed with a new identity. Persist per-item status and bounded safe diagnostics, and reconcile unknown outcomes before retry. Test a commit followed by a lost acknowledgment as well as validation rejection. The in-memory integer parser still helps with input validation, but it does not supply payment atomicity, durable receipts, or a safe retry protocol.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

What should you do before adopting this repair?
TRANSFER THE IDEA

Recreate the repair independently

Add a regression case in which the first, middle and last records are invalid. Start from the symptoms and write your own regression assertion before opening the reference.

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: preserve partial parsing evidence

Continue after malformed integer text and retain ordered successes and failed keys.

The contract

  • records is a list of (string key, string text) tuples. int(text) defines valid text, including signs and whitespace.
  • Return a tuple (values, errors) of new lists: values contains (key, integer) successes; errors contains failed keys. Preserve relative order and duplicates in each list.
  • Catch only ValueError from conversion. Unsupported values such as None raise TypeError. Empty input returns ([], []); do not mutate records.
Guided: preserve partial parsing evidencePYTHON 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 failure
    r = parse_items([('a', '2'), ('b', 'bad'), ('c', '3')])
    assert type(r) is tuple and r == ([('a', 2), ('c', 3)], ['b']) and all(type(x) is list for x in r)
  2. empty ownership
    x = []
    r = parse_items(x)
    assert type(r) is tuple and r == ([], []) and r[0] is not x and r[1] is not x and r[0] is not r[1]
  3. edge failures
    assert parse_items([('a', 'x'), ('b', '1'), ('c', 'y')]) == ([('b', 1)], ['a', 'c'])
  4. signs and duplicates
    r = parse_items([('a', '-2'), ('a', ' +3 '), ('a', 'bad')])
    assert r == ([('a', -2), ('a', 3)], ['a']) and all(type(v) is int for k, v in r[0])
  5. narrow errors
    raised = False
    try:
        parse_items([('a', None)])
    except TypeError:
        raised = True
    assert raised
  6. preserve records
    x = [('a', '2'), ('b', 'bad')]
    r = parse_items(x)
    assert r == ([('a', 2)], ['b']) and x == [('a', '2'), ('b', 'bad')]
    r[0].append(('z', 8))
    assert x == [('a', '2'), ('b', 'bad')]
    What is preserved, and what is not guaranteed?

    The loop preserves each occurrence's category and relative order, with n conversions and O(n) result entries. Conversion cost depends on text length. It does not roll back external effects or validate domain-specific ranges.

    GUIDED PRACTICE

    Guided: retain detail without losing totals

    Return a bounded display sample and a total failure count from supplied failed identifiers.

    The contract

    • keys is an already-materialized list of failed string IDs. limit is a nonnegative integer.
    • Return a tuple (new sample list, exact integer total), keeping the first limit occurrences and counting every input occurrence.
    • Preserve input and repeated IDs. Zero limit retains no details; empty input has total zero. This is a view policy, not streaming failure collection.
    Guided: retain detail without losing totalsPYTHON 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. truncated sample
      r = error_sample(['a', 'b', 'c'], 2)
      assert type(r) is tuple and r == (['a', 'b'], 3) and type(r[0]) is list and type(r[1]) is int
    2. zero detail budget
      assert error_sample(['a', 'b'], 0) == ([], 2)
    3. empty ownership
      x = []
      r = error_sample(x, 3)
      assert type(r) is tuple and r == ([], 0) and r[0] is not x and type(r[1]) is int
    4. duplicates
      assert error_sample(['a', 'a', 'b'], 2) == (['a', 'a'], 3)
    5. large budget
      assert error_sample(['x'], 9) == (['x'], 1)
    6. sample ownership
      x = ['a', 'b']
      r = error_sample(x, 2)
      assert r == (['a', 'b'], 2) and r[0] is not x
      r[0].append('c')
      assert x == ['a', 'b']
      Can callers retry all failures using this sample alone?

      Not if it was truncated. The slice uses O(min(n, limit)) extra references, while the supplied list already retains n IDs. A complete retry manifest requires separate full outcome storage.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: reject all local preparation on any invalid item

      Change from partial parsing to atomic validation with an explicit acceptance flag.

      The contract

      • records is a list of (string key, string text) tuples. Use int(text); catch only ValueError.
      • Return (True, new list of all (key, integer) pairs) if all parse, or (False, new empty list) on any malformed text.
      • Empty input is accepted as (True, []). Preserve duplicates/order and input. This prepares data only; it performs no transaction or external effects.
      Transfer: reject all local preparation on any invalid itemPYTHON 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. all accepted
        r = atomic_parse([('a', '2'), ('b', '3')])
        assert type(r) is tuple and r == (True, [('a', 2), ('b', 3)]) and type(r[0]) is bool and type(r[1]) is list
      2. discard successful prefix
        assert atomic_parse([('a', '2'), ('b', 'bad'), ('c', '3')]) == (False, [])
      3. empty is valid
        x = []
        r = atomic_parse(x)
        assert type(r) is tuple and r == (True, []) and r[0] is True and r[1] is not x
      4. failure at boundaries
        r = atomic_parse([('a', 'bad')])
        s = atomic_parse([('a', '1'), ('b', 'bad')])
        assert r == (False, []) and r[0] is False and s == (False, []) and r[1] is not s[1]
      5. duplicate signed inputs
        assert atomic_parse([('a', '-2'), ('a', ' +3 ')]) == (True, [('a', -2), ('a', 3)])
      6. ownership and narrow errors
        x = [('a', '2')]
        r = atomic_parse(x)
        assert r == (True, [('a', 2)]) and x == [('a', '2')] and r[1] is not x
        raised = False
        try:
            atomic_parse([('a', None)])
        except TypeError:
            raised = True
        assert raised
        Why is this not a rollback mechanism for payments?

        It only creates local proposed values and discards them on invalid text. There are up to n conversions and O(n) preparation entries. External writes require their own atomic commit or explicit compensation/reconciliation design.

        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

        The underlying mechanism

        Atomic validation is a different policy: reject the whole prepared result if any record is invalid. No external operation should start before validation succeeds when this promise is required.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Not every batch can safely keep partial success. Preparation can separate checking data from applying external effects, but cannot alone make several remote effects atomic.

        Words you will see

        Atomic
        Observed as all accepted or all rejected under the stated boundary.
        Preparation
        Constructing and validating proposed data before applying it.
        Commit
        The step that makes a prepared change authoritative.

        Change the requirement explicitly

        The model prepares two integers, observes malformed text, and clears the prepared result. Its empty list is accompanied by a False validity flag. That flag distinguishes rejected input from a valid empty batch.

        The local model never writes externally. Clearing a Python list cannot undo a payment already made, so moving a clear call into an external batch would not provide atomicity. Use a suitable transaction, staged commit or explicit compensation design for that integration.

        Know the trade-off

        Atomic rejection simplifies a caller's accepted/rejected decision but forces correction of every bad item before any is accepted. Partial processing can keep independent good items but requires per-item reconciliation. Choose from dependencies and business guarantees, not catch syntax.

        Preparing n results retains O(n) local entries before commit. For large inputs, streaming to a validated staging area can change storage ownership. A transfer exercise below asks for an explicit status plus values; a naked [] is no longer an adequate output.

        The original example, step by step

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

        1. prepared = []

          Keep uncommitted local values.

        2. prepared.append(int(text))

          Prepare only successful conversions.

        3. valid = False

          Record that the entire proposed batch is invalid.

        4. prepared.clear()

          Discard local preparation, not external side effects.

        5. break

          No later value can rescue this reject-all policy.

        An exception unwinds to the nearest matching handler; placing that handler outside the loop aborts the remaining iterations. Database transactions and external side effects require additional coordination beyond this in-memory parser.

        Predict before you run

        Will this model return a prepared 2?

        Atomic-validation model, not an external transactionPYTHON 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.

        Validate an all-good batch.

        Try: Replace 'bad' with '4'.

        The output becomes True [2, 4, 3].

        Move failure to the last item.

        Try: Use ['2', '3', 'bad'].

        The whole preparation is still rejected, showing failure position does not change atomic validation.

        Before you move on

        Under atomic validation, how should an empty valid batch differ from a rejected batch?

        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

        Use explicit status: (True, []) for valid emptiness and (False, []) for rejection. The values alone cannot express this difference.

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

        Alternatives and operational trade-offs

        Bound error detail separately from error count. A report can retain a small ordered sample while still counting every declared failure.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A malformed large batch can fill memory with diagnostics. Reconciliation needs totals, but callers may not need every raw failed item in an in-memory report.

        Words you will see

        Sample limit
        The most error identifiers retained for display.
        Total failures
        The count of all declared failed occurrences, including omitted details.
        Omitted count
        Failures whose detail was not retained.

        Avoid moving the memory problem into errors

        The example models three failed identifiers and keeps only the first two for display. Total remains three. The omitted count is total minus retained count, so a caller can see that the visible list is incomplete.

        This small example starts with an existing list to explain the rule. A production bounded reporter would increment total while streaming and append only until the sample limit, rather than first materializing every failure. Never label this source itself constant-space streaming.

        Keep retry selection honest

        A bounded sample is not a complete retry manifest. Keep durable full outcomes elsewhere if every failed occurrence must be retried. Repeating the entire input may duplicate earlier external successes, while retrying only the sample silently misses omitted failures.

        Copying a prefix of size k uses O(k) reference storage; the supplied failed list still uses O(n). In a streaming implementation, the retained sample can be O(k) plus a counter, with accounting for the growing integer count. Redact sensitive payloads and keep stable safe identifiers.

        The original example, step by step

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

        1. failed_keys = ['a', 'b', 'c']

          Supply three already-known failures for the model.

        2. sample = failed_keys[:limit]

          Retain a display prefix of two.

        3. total = len(failed_keys)

          Count every failed occurrence, not just displayed ones.

        4. print(total, total - len(sample))

          Report total three and one omitted detail.

        Some batches require atomic rejection; others allow partial success. Document ordering, duplicate IDs, retry selection and error retention. Do not retry every item blindly after partial side effects or leak raw personal records into error logs.

        Predict before you run

        How many error details are omitted?

        A bounded diagnostic-view modelPYTHON 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.

        Remove the detail budget.

        Try: Set limit = 0.

        The sample is empty, total remains three, and omitted becomes three.

        Show all details.

        Try: Set limit = 5.

        All three keys fit and omitted becomes zero; no extra errors are invented.

        Before you move on

        With five failures and sample limit zero, how many failures should the report count?

        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

        Five. It retains no detail and reports five omitted identifiers. A zero display budget must not erase the existence of failures.

        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.