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 67 / PROJECTS AND ASSESSMENTS

Project: a streaming CSV report

Build a CSV reporting tool that totals nonnegative study minutes by topic, understands quoted fields and reports malformed records explicitly. Start with a pure stream-based calculation before adding real input/output files.

AdvancedProject 40 min core+25 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 ready to reason about Python internals, resource boundaries and the listed prerequisites.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 40 minutes; optional deep dive: 25 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
  • Translate requirements into contracts
  • Implement and test a complete small slice
  • Explain production gaps and next increments
BUILD / TEST / EXPLAIN

Project brief and review

Build a CSV reporting tool that totals nonnegative study minutes by topic, understands quoted fields and reports malformed records explicitly. Start with a pure stream-based calculation before adding real input/output files. Reading time does not include your independent implementation time.

Requirements

  • Parse CSV with csv.DictReader.
  • Require topic and minutes columns; validate every record.
  • Aggregate without retaining every input row.
  • Keep input and output file operations separate.

Acceptance checklist

These self-checks are page-local, not saved or automatically judged.

Further increments

  • Add a CLI accepting an input path and output path.
  • Write output atomically and add a bounded invalid-row report.

Build this as a multi-file project: Streaming CSV reporter

A one-pass text-stream calculation, not filesystem publication. Extra unique named columns are allowed; blank physical lines are skipped by DictReader. Each field is limited to 4096 characters and distinct topics to 1000 by default; parser buffers and the input source still consume memory. Atomic file output remains a further increment. The lesson's single-file browser runner does not import these files.

  1. Preview and download the starter. In Standalone Playground, sign in and choose Import JSON as a new local project. Importing replaces local editor files only after its existing unsaved-edit confirmation; export your work first.
  2. Implement records(stream, max_topics=1000) and report(stream, max_topics=1000) in reporter.py. Use strict csv.DictReader, unique required topic/minutes headers, regular row lengths, stripped nonblank topics and stripped ASCII decimal minute digits only. Preserve case, first-topic order, duplicates and zero. Fail with safe record context, never a partial report; do not close or rewind the caller's stream.
  3. Implement csv_counts(text) in transfer.py using the same validation, but count valid sessions, including zero-minute rows, rather than summing minutes. A late invalid minute still fails. Add a case where session count and duration total differ.
  4. Read the one-pass and bounded-cardinality tests before implementing. Work is linear in parsed input plus field lengths and retains O(k) groups, not all rows. Explain why streaming does not bound distinct-topic memory or prove atomic output.
  5. Save snapshot explicitly, then Run current files to execute main.py's 13 public standard-library tests. The suite stops at the first failure; the untouched starter raises a real NotImplementedError. Inspect the named failing case, edit and rerun. Add an original test and explain why it would catch a tempting wrong approach.
  6. Stop an active program before changing its baseline. Export current project JSON to keep your exact files; import the original starter as a separate local project to reset, with the same edit-loss confirmation. A saved version can be restored explicitly. Record your saved artifact and limitations separately if private project self-review is enabled.

Public tests are visible and editable, not exhaustive grading or proof that you worked without the reference. No completion, reading milestone or judge acceptance is awarded. Run needs the independently enabled approved Python Playground runtime; if unavailable, source editing/export remains available without a fallback. Frameworks, cloud services, live APIs and persistent database sessions remain unsupported. For local work, download all previewed source files into the same empty folder and run python main.py from that folder in your own Python 3.11+ environment. Downloads do not install Python or provide offline server execution.

References are excluded by default. Including them changes only the new download, never your current lesson or saved project.

01

Project brief and boundaries

A streaming CSV report reads one record at a time and retains totals, not a list of every parsed row.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Reports can exceed the memory available for all input rows. A text-stream core also avoids tying business logic to paths.

Words you will see

CSV
A text table format with delimiters and quoting rules.
Stream
A source that supplies text progressively.
Cardinality
The number of distinct grouping keys.

Decompose the report contract

The input has topic and minutes columns. Require the header even when there are no records. Use csv.DictReader because quoted commas belong inside fields. Hand splitting on commas would turn one topic into multiple fields and silently corrupt grouping.

The core consumes a stream and returns a fresh topic-to-minute mapping. Stream position advances by design; this is not mutation of caller row dictionaries. The output adapter owns formatting and publication. Keep the stream open and closing policy with whichever adapter opened it.

Sequence implementation and bound state

Begin with header validation and empty data, add one row, then repetitions and quoted fields, then invalid rows and useful errors. Only afterwards add file paths. The example below shows quoted framing with StringIO, a text stream held in memory.

Streaming removes the need to retain n rows, but k distinct topics still need O(k) totals storage under bounded key sizes. Set field-size and cardinality policies for larger use. Browser-local StringIO does not prove a real large file was processed or an output was safely replaced.

The original example, step by step

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

  1. from io import StringIO

    Choose a browser-local text fixture.

  2. rows = csv.DictReader(StringIO(text))

    Read named columns with CSV quoting rules.

  3. row = next(rows)

    Read a single data record.

  4. print(row["topic"])

    Observe that the quoted comma stays within one topic.

Build a CSV reporting tool that totals nonnegative study minutes by topic, understands quoted fields and reports malformed records explicitly. Start with a pure stream-based calculation before adding real input/output files.

Conceptual streaming ownership and data flow

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

  1. Text adapterOwn opening/closing and supply a text stream.
  2. CSV recordsConsume each parsed record once; validate before accumulating.
  3. TotalsRetain only distinct-topic totals, then pass the complete mapping to an output adapter.
Predict before you run

Does the topic retain its comma?

Let the CSV reader handle a quoted commaPYTHON 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.

Use a different delimiter inside quotes.

Try: Change the topic text to "trees, basics".

The full phrase still becomes one topic.

Add a second data row.

Try: Append loops,0 followed by a newline to text.

The first next call is unchanged; iterate rows to consume the second record.

Before you move on

A quoted topic is "arrays, review". How many grouping keys should that single row contribute?

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

One. CSV quoting protects the comma inside the topic; the duration belongs to the separate minutes column.

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

Design a testable slice

Header validation and record validation are different stages. A table can have correct columns and still contain unacceptable data.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Converting invalid input to zero or skipping it creates believable but incorrect totals. Explicit failure keeps corrupt reports from looking complete.

Words you will see

Header
The first CSV record naming columns.
Row context
A safe record number explaining where validation failed.
Fail-fast report
A report that returns no result when any required record is invalid.

Choose policies before adding code

Require topic and minutes exactly once; decide whether extra columns are allowed. A row with too many fields can be represented under a None key by DictReader. A short row can give a missing value of None. Validate these shapes explicitly instead of assuming header presence makes every row regular.

For the guided increment, duplicate headers and irregular row lengths are rejected. Minutes are nonnegative decimal integer text after trimming. The complete existing reference uses int and is intentionally less strict about shape and spelling; preserve it, but do not describe it as exhaustive validation.

Make errors actionable without leaking records

Keep a logical record counter and raise a short message such as record 2: invalid minutes. Quoted newlines mean logical record number and physical line number can differ. The sample demonstrates conversion and a controlled error without printing private field contents.

Test a bad row after a valid row and verify there is no success-shaped partial mapping. The input text string stays unchanged; a stream is consumed as documented. File encoding failures and output replacement remain local adapter tests, not browser execution capabilities.

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 = ["7", "-2", "0"]

    Supply a valid value before an invalid one.

  2. for number, text in enumerate(values, start=1):

    Count logical values beginning at one.

  3. if minutes < 0:

    Reject a parsed negative value.

  4. print(f"record {number}: invalid minutes")

    Show safe context rather than echoing raw input.

A function accepting a text stream is easy to test with StringIO and easy to reuse with an open file. The aggregation owns a dict of topic totals; parsing and validation are separate from formatting. State the assumed maximum number and size of distinct topics.

Predict before you run

Which record triggers the diagnostic?

Report a safe logical record errorPYTHON 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.

Accept all three values.

Try: Replace "-2" with "2".

Nothing prints because there is no invalid value.

Test conversion failure.

Try: Replace "-2" with "two".

The same safe record-2 diagnostic appears from int's ValueError.

Before you move on

The header is valid but a later minutes cell is absent. Should it count as zero?

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. Missing duration is invalid, not a zero-minute session. Reject the record with context and return no report.

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

A complete stream-based report

The original stream report is a complete calculation slice, not a file-publishing application.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A small working reference helps connect CSV parsing, validation and grouping while keeping external I/O out of unit tests.

Words you will see

DictReader
A CSV reader mapping header names to field values.
Required columns
The fields that must be present for this calculation.
Borrowed stream
A stream supplied by another owner, which this core consumes but does not close.

Walk through the preserved source

DictReader reads the header on demand. The subset test requires both named columns but allows other headers. For each row the topic is trimmed, minutes is converted with int, then negative minutes or a blank topic is rejected. Repeated lists rows add 10 and 15.

The header-only assertion distinguishes valid empty data from missing columns. The function consumes its stream and returns a new dictionary. It does not close the supplied stream. A caller that wants to read again must explicitly seek or supply a fresh stream; do not hide that stateful boundary.

State reference limits precisely

This reference does not add record context to every error or reject all duplicate headers and irregular rows. Missing minutes can produce a TypeError. Independent project work should test and tighten these policies rather than pretending the short sample already satisfies every production hardening goal.

No path is opened and no report file is written. Expected total space grows with distinct topics, not the input record count when cardinality is bounded. Validate this by inspecting retained state and using a one-pass fixture, not by claiming that a short sample measured a large-file memory ceiling.

The original example, step by step

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

  1. rows = csv.DictReader(stream)

    Parse the borrowed text stream lazily.

  2. totals = {}

    Retain only totals, not a list of parsed records.

  3. minutes = int(row['minutes'])

    Convert field text before range checking.

  4. totals[topic] = totals.get(topic, 0) + minutes

    Accumulate repeated topics in first-seen order.

The reference implements the stream-processing slice with standard-library CSV parsing and an empty-input assertion. Path safety and atomic file output belong to the separate I/O adapter.

Predict before you run

How much does lists contribute?

A complete stream-based 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.

Keep a comma inside a topic.

Try: Replace loops,5 with "loops, review",5 in text.

The parser returns one topic named loops, review with total five.

Remove the required header.

Try: Change minutes in the header to duration.

The explicit Missing columns error occurs before aggregation.

Before you move on

After report consumes a StringIO, can calling report again on that same current position reliably reproduce the result?

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 stream is exhausted. Supply a new stream or explicitly rewind if that is part of the caller's policy.

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

Define the stream core and file-adapter contract

The project totals nonnegative study minutes by topic from CSV containing topic and minutes columns. A text-stream core owns parsing and aggregation, while an adapter owns opening paths, encoding, and publishing output. csv.DictReader respects quoted commas and record framing that manual splitting would break. State the maximum field length and distinct-topic count. Streaming rows avoids storing the entire input, but the totals dictionary still grows with the number and size of distinct topics.

The reference accepts a StringIO stream and returns lists 25 and loops 5 for its supplied rows. It checks required headers, strips topics, converts minutes, and rejects blank topics or negative minutes. Its empty valid-header assertion distinguishes a valid zero-record file from a file with missing columns. It does not consistently add row context to every conversion error or reject every malformed CSV shape; those are requirements for the independent implementation, not evidence already supplied by the fixture.

Build the report in numbered, inspectable increments

1. Implement header validation and the empty report. 2. Add one valid record and repeated-topic accumulation. 3. Validate each row with safe record context and test quoted topic fields. 4. Add formatting as a separate pure step. 5. Add real file input and output only after the stream core passes. This sequence keeps the first acceptance slice independent of paths and makes malformed data easier to diagnose without opening the reference solution.

Decide policy for duplicate headers, extra fields, missing minutes, whitespace-only topics, and blank rows. DictReader can represent irregular rows in ways that need explicit checking, so header presence alone is insufficient. Preserve the stated fail-fast contract unless you intentionally design a separate partial-report mode with bounded errors. Do not silently coerce invalid minutes to zero or skip corrupt records, because either choice can produce plausible totals that no longer represent the input.

Prove unit and integration acceptance separately

Unit tests should include the valid header with no records, repeated topics, zero minutes, a quoted comma in a topic, invalid integer text, negative minutes, missing columns, and a bad row after valid data. Assert no complete result is returned on failure. Use a one-pass stream to expose accidental re-reading and a large bounded-cardinality generated input to inspect retention. Compare high-cardinality behavior separately rather than extrapolating from many repetitions of two topics.

For file integration, verify explicit encoding, permitted paths, destination overwrite policy, and cleanup when reading or writing fails. Write a completed report through a staging-and-replacement design appropriate to the target filesystem, and test that a failed run does not leave a partial report under the final name. Treat crash durability and cross-filesystem replacement as separate concerns. The existing StringIO fixture proves none of these real filesystem properties, so label them as additional acceptance evidence.

Budget resources and independent project effort

Expected processing time is linear in parsed input size plus formatting work, while aggregation retains O(k) topic entries and parser buffers. Very large fields and totals affect those costs. Add cardinality and error-sample limits, or choose database or external aggregation if exact results exceed memory. Bound output size and handle storage exhaustion explicitly. Sorting a formatted report adds materialization and ordering costs that the unsorted dictionary contract did not require.

Allocate separate focused sessions for stream logic, adversarial CSV tests, and file integration; the displayed lesson duration is not a guarantee of completing all hardening. Before viewing the reference, retain your own failing tests and implementation attempts. Afterward, document which differences corrected a misunderstanding and rebuild one requirement unaided. A self-review should list actual observed cases and unsupported features, not claim that a few parsed rows establish a deployable reporting tool.

Transfer question: The reporter must emit sorted totals for more topics than fit in memory. How would you revise the architecture?

Keep parsing and validation streaming, but replace the unbounded dictionary with an external aggregation stage, such as a database or sorted runs merged by normalized topic. Define disk quotas, record encoding, collation, and cleanup for intermediate state. Only publish the final sorted report after successful aggregation. Test equivalent totals against the small in-memory version, then exercise distinct-key growth, storage exhaustion, and interrupted merge cleanup. Quoted CSV parsing remains necessary at input; external grouping does not justify manual splitting. State that this extension requires new integration evidence beyond the original StringIO calculation.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

When is this project ready for your self-review?
TRANSFER THE IDEA

Build before opening the reference

Parse CSV with csv.DictReader. Require topic and minutes columns; validate every record. Aggregate without retaining every input row. Keep input and output file operations separate. Demonstrate the acceptance cases and document any unsupported requirement.

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

Validate required CSV headers

Guided increment 1: inspect only the CSV header and return its column names in their original order.

The contract

  • Input is CSV text with ordinary valid CSV syntax. The header must contain topic and minutes exactly once; extra distinct column names are allowed.
  • Return a new list of header strings in source order without trimming or renaming them. Missing input/required columns and any duplicate header raise ValueError.
  • This increment reads only the header, not data records; the immutable input text stays unchanged.
  • Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent project.
Validate required CSV headersPYTHON 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. Required columns
    import copy
    supplied = "topic,minutes\n"
    before = copy.deepcopy(supplied)
    result = csv_headers(supplied)
    expected = ["topic","minutes"]
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    assert supplied == before, "Caller input changed"
    
  2. Missing input
    import copy
    supplied = ""
    before = copy.deepcopy(supplied)
    try:
        result = csv_headers(supplied)
    except ValueError:
        result = "ValueError"
    expected = "ValueError"
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    assert supplied == before, "Caller input changed"
    
  3. Reordered extra column
    import copy
    supplied = "minutes,note,topic\n"
    before = copy.deepcopy(supplied)
    result = csv_headers(supplied)
    expected = ["minutes","note","topic"]
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    assert supplied == before, "Caller input changed"
    
  4. Duplicate required column
    import copy
    supplied = "topic,minutes,topic\n"
    before = copy.deepcopy(supplied)
    try:
        result = csv_headers(supplied)
    except ValueError:
        result = "ValueError"
    expected = "ValueError"
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    assert supplied == before, "Caller input changed"
    
  5. Missing minutes
    import copy
    supplied = "topic,note\n"
    before = copy.deepcopy(supplied)
    try:
        result = csv_headers(supplied)
    except ValueError:
        result = "ValueError"
    expected = "ValueError"
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    assert supplied == before, "Caller input changed"
    
  6. Quoted extra column
    import copy
    supplied = 'topic,minutes,"note, detail"\n'
    before = copy.deepcopy(supplied)
    result = csv_headers(supplied)
    expected = ["topic","minutes","note, detail"]
    assert type(result) is type(expected), "Wrong result type"
    assert result == expected, "Wrong result value"
    assert supplied == before, "Caller input changed"
    
    How does validate required csv headers support an independent project, and what remains untested?

    This isolates header acceptance in O(h) expected work and space for h columns. It does not validate any record or establish streaming-file or publication behavior.

    GUIDED PRACTICE

    Stream a strict text report

    Guided increment 2: process one parsed record at a time and sum validated minute fields.

    The contract

    • Input is valid CSV syntax as text. Require unique headers with topic and minutes; allow extra columns but require regular row lengths.
    • Topic is nonblank after stripping. Minutes is stripped ASCII decimal digits only, including zero; signs, negatives, decimals and missing cells raise ValueError.
    • Return a fresh first-seen-order totals dict; quoted topics and duplicates work. Fail with no partial result and keep text unchanged. Do not materialize all rows.
    • Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent project.
    Stream a strict text 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.

    Inspect 6 public checks

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

    1. Quoted repeat and order
      import copy
      supplied = 'topic,minutes\n"b, review",2\na,0\n"b, review",3\n'
      before = copy.deepcopy(supplied)
      result = csv_totals(supplied)
      expected = {"b, review":5,"a":0}
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      assert supplied == before, "Caller input changed"
      assert list(result) == ["b, review", "a"], "Wrong topic order"
    2. Header only
      import copy
      supplied = "topic,minutes\n"
      before = copy.deepcopy(supplied)
      result = csv_totals(supplied)
      expected = {}
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      assert supplied == before, "Caller input changed"
      
    3. Whitespace and zero
      import copy
      supplied = "topic,minutes\n x , 0 \n"
      before = copy.deepcopy(supplied)
      result = csv_totals(supplied)
      expected = {"x":0}
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      assert supplied == before, "Caller input changed"
      
    4. Late negative fails
      import copy
      supplied = "topic,minutes\na,3\nb,-1\n"
      before = copy.deepcopy(supplied)
      try:
          result = csv_totals(supplied)
      except ValueError:
          result = "ValueError"
      expected = "ValueError"
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      assert supplied == before, "Caller input changed"
      
    5. Extra row cell
      import copy
      supplied = "topic,minutes\na,2,extra\n"
      before = copy.deepcopy(supplied)
      try:
          result = csv_totals(supplied)
      except ValueError:
          result = "ValueError"
      expected = "ValueError"
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      assert supplied == before, "Caller input changed"
      
    6. Missing duration
      import copy
      supplied = "topic,minutes\na\n"
      before = copy.deepcopy(supplied)
      try:
          result = csv_totals(supplied)
      except ValueError:
          result = "ValueError"
      expected = "ValueError"
      assert type(result) is type(expected), "Wrong result type"
      assert result == expected, "Wrong result value"
      assert supplied == before, "Caller input changed"
      
      How does stream a strict text report support an independent project, and what remains untested?

      The generator validates and yields one row at a time; the result retains O(k) totals for k topics. StringIO holds this fixture's source text, so this is not a measured large-file memory claim. Real files and atomic output remain separate.

      TRANSFER / TRY BEFORE OPENING HINTS

      Count valid CSV sessions

      Transfer: count valid session rows per topic instead of summing their durations, including zero-minute rows.

      The contract

      • Use the same strict headers, regular row shape, topic and decimal-minute rules as csv_totals.
      • Return a fresh first-seen-order dict of occurrence counts, including every valid zero-minute row.
      • Validate minute values even though they are not summed. Any invalid record raises ValueError, including late failures; text is unchanged.
      • Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent project.
      Count valid CSV sessionsPYTHON 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. Count not duration
        import copy
        supplied = "topic,minutes\nb,0\na,7\nb,9\n"
        before = copy.deepcopy(supplied)
        result = csv_counts(supplied)
        expected = {"b":2,"a":1}
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        assert supplied == before, "Caller input changed"
        assert list(result) == ["b", "a"], "Wrong topic order"
      2. Empty valid report
        import copy
        supplied = "topic,minutes\n"
        before = copy.deepcopy(supplied)
        result = csv_counts(supplied)
        expected = {}
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        assert supplied == before, "Caller input changed"
        
      3. Quoted zero session
        import copy
        supplied = 'topic,minutes\n"a, b",0\n'
        before = copy.deepcopy(supplied)
        result = csv_counts(supplied)
        expected = {"a, b":1}
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        assert supplied == before, "Caller input changed"
        
      4. Invalid duration still fails
        import copy
        supplied = "topic,minutes\na,no\n"
        before = copy.deepcopy(supplied)
        try:
            result = csv_counts(supplied)
        except ValueError:
            result = "ValueError"
        expected = "ValueError"
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        assert supplied == before, "Caller input changed"
        
      5. Blank topic still fails
        import copy
        supplied = "topic,minutes\n ,2\n"
        before = copy.deepcopy(supplied)
        try:
            result = csv_counts(supplied)
        except ValueError:
            result = "ValueError"
        expected = "ValueError"
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        assert supplied == before, "Caller input changed"
        
      6. Late missing duration
        import copy
        supplied = "topic,minutes\na,2\nb,\n"
        before = copy.deepcopy(supplied)
        try:
            result = csv_counts(supplied)
        except ValueError:
            result = "ValueError"
        expected = "ValueError"
        assert type(result) is type(expected), "Wrong result type"
        assert result == expected, "Wrong result value"
        assert supplied == before, "Caller input changed"
        
        How does count valid csv sessions support an independent project, and what remains untested?

        Only the reducer changes; validation remains necessary to count real accepted sessions. Expected time is O(n) plus field lengths and space O(k) totals. This is a browser-local transfer, not independent evidence for file publication.

        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

        Production hardening is separate

        Publishing is a separate operation from calculation. A complete report value should exist before any final-looking output is exposed.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Writing rows while still validating input can leave a corrupt half-report when a later row fails.

        Words you will see

        Formatting
        Turning a result into a chosen presentation.
        Atomic replacement
        A filesystem operation that switches a published name as one step under stated conditions.
        Integration test
        A check of collaborating real boundaries rather than only pure functions.

        Keep formatting independently testable

        Define whether output order follows first appearance or is sorted, how the header is spelled, and how topics with commas are quoted. Use csv.writer for CSV output rather than constructing lines manually. The sample writes to StringIO so formatting is inspectable without filesystem authority.

        Sorting this presentation is an explicit output-adapter choice; it does not change the domain result's first-occurrence order. The writer owns only its new text buffer. Numeric totals remain numbers until serialization. Quoting must protect topics just as carefully on output as on input.

        Plan real file acceptance separately

        A local adapter owns safe paths, encoding, newline handling, output-size policy and cleanup. Atomic replacement needs a platform-aware design and tests; no in-memory buffer demonstrates crash safety. Do not erase an existing good report before the new report has been validated.

        Browser Python can exercise the formatter with StringIO. Real path permissions, replacement failures and disk-full behavior need a local integration environment. The guided exercises intentionally stop before that boundary and do not claim a finished installed reporting tool.

        The original example, step by step

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

        1. totals = {"trees, review": 8, "loops": 0}

          Start only with a complete domain result.

        2. writer = csv.writer(output, lineterminator="\n")

          Choose stable newline formatting explicitly.

        3. writer.writerows(sorted(totals.items()))

          Sort only the displayed rows; the source mapping is unchanged.

        4. print(output.getvalue(), end="")

          Observe generated text without adding a second terminal newline.

        File access requires explicit encodings, allowed paths and a policy for replacing existing reports. Add file-size/field/cardinality limits, safe errors and integration tests using temporary files. This reference does not access a real user's filesystem.

        Predict before you run

        Why is trees, review quoted?

        Format a complete report in memoryPYTHON 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 presentation order.

        Try: Remove sorted and pass totals.items() directly.

        trees, review appears before loops, matching insertion order.

        Add a newline within a topic.

        Try: Change the first topic to "trees\nreview".

        The CSV writer quotes the multiline field; output spans physical lines.

        Before you move on

        A topic contains a comma. Should the formatter remove it to keep two columns?

        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. Preserve the topic and let csv.writer quote the field. Removing content would change the report data.

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

        Review and transfer

        A transfer report may count valid sessions instead of summing their minutes. Parsing can stay while the aggregation meaning changes.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Separating parser, validator and reducer makes a changed product question easier to implement without rewriting every boundary.

        Words you will see

        Reducer
        A rule combining many accepted records into a summary.
        One-pass
        Consuming an input sequence without restarting it.
        Bounded cardinality
        A stated limit on the number of distinct result groups.

        Change the unit without weakening validation

        A session-count report adds one per valid row, including a zero-minute row. It still validates minutes because invalid records must not count as real sessions. A total of zero minutes can represent multiple sessions; do not confuse the two outputs.

        Write a new acceptance case in which two rows for one topic have minutes 0 and 9. Minutes total nine, but session count two. Keep header, quoting, row-shape, order and ownership policies unchanged unless you explicitly revise their contracts.

        Use tests to expose accidental retention

        The sample uses a generator of topic names and counts them without materializing a list. A production CSV test can supply a one-pass stream that rejects seeking and inspect that the code never builds list(rows). Correct short output alone does not prove a memory bound.

        Expected work is linear in accepted rows under ordinary bounded-key dictionary assumptions. State remains proportional to distinct topics. Build this transfer without the minute-report reference open and explain the changed update. Browser-local tests still do not cover actual file publication.

        The original example, step by step

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

        1. topics = (topic for topic in ["loops", "loops", "lists"])

          Create a one-pass generator for this local fixture.

        2. counts = {}

          Store only one total per distinct topic.

        3. counts[topic] = counts.get(topic, 0) + 1

          Add one session rather than minutes.

        4. print(list(topics))

          Demonstrate the generator has been consumed; the reducer itself never built this list.

        After implementation, explain the boundary cases and change one requirement without rewriting unrelated behaviour. Add a CLI accepting an input path and output path. Write output atomically and add a bounded invalid-row report. Keep a record of what you tested; a viewed reference is not proof you independently completed the project.

        Predict before you run

        Why is the final list empty?

        Count sessions in one passPYTHON 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 another occurrence.

        Try: Add "lists" to the generator fixture list.

        lists becomes two while first-seen order remains unchanged.

        Try no records.

        Try: Use an empty fixture list.

        Both the count result and the exhausted-source display are empty.

        Before you move on

        Three valid rows for loops contain 0, 0 and 5 minutes. What should the session-count transfer report return?

        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

        loops has three sessions. Zero-minute records remain valid and each contributes one occurrence.

        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.