CS 101 — Programming Foundations with Python — Reasoning and Practice

Full teaching sequence and cumulative subject work

A complete ledger pipeline with a falsifiable specification — primary material, constructed-response tasks, complete worked model and changed-case examination →

Use this workbook with the full assigned readings. Work independently, then compare each explained solution. Practice and projects are voluntary. Cases and datasets are fictional unless a primary passage is explicitly named.

Contracts, representation and exact money

A function contract connects representation to a business rule. A price stored as integer cents makes addition exact for whole-cent inputs, but it does not decide how to round a percentage discount. That decision belongs in the specification. Separate conversion, validation, computation and display. Otherwise a caller may silently supply dollars where cents are expected, or accept a rounded intermediate result as if it were exact.

Validation also needs a policy for types. Python booleans behave like integers in some operations, yet True is rarely an acceptable invoice amount. Explicitly rejecting booleans can be a defensible boundary rule. Describe that rule rather than treating one implementation choice as universal. A rejected record must not change an already accumulated total.

Worked problem

An invoice contains three visits at 1,995 cents each. A 10% discount applies to the whole invoice, rounded to the nearest cent with halves rounded upward. Compare discounting the total with rounding each discounted visit.

Trace the complete solution
  1. The undiscounted total is 3 × 1,995 = 5,985 cents. The exact discounted invoice is 5,386.5 cents, which rounds upward to 5,387 cents.

  2. Each discounted visit is 1,795.5 cents and rounds to 1,796. Three individually rounded visits total 5,388 cents. The one-cent difference comes from when rounding occurs, not a multiplication error.

  3. Implement the stated invoice-level policy using exact integer arithmetic: for a nonnegative total T and integer discount d, rounded cents are (T × (100 − d) + 50) // 100. The formula encodes this specific half-up rule; it is not a general policy for negative credits.

  4. Reject invalid quantities before computing the invoice. Format cents as dollars only at the display boundary. Record the rounding policy in tests and documentation.

Independent transfer problem

Four visits cost 1,249 cents each, with a 15% invoice-level discount. Calculate the payable amount, then explain why a refund should not automatically reuse the nonnegative half-up formula.

Compare the reasoning and result

Four visits total 4,996 cents. Multiplying by 85 gives 424,660 hundredths of a cent; (424,660 + 50) // 100 = 4,247 cents, or $42.47. A negative credit introduces a tie-direction policy: adding 50 and flooring is not symmetric half-away-from-zero rounding. Specify whether the credit reverses the original rounded invoice or is rounded independently, then test positive, zero and negative boundaries.

Open the unit and assigned readings →

Iteration, invariants and partial failure

An invariant states what an accumulator means after a processed prefix. For a validated transaction stream, total is the sum of accepted amounts and accepted is the number of accepted records. A useful invariant includes rejected records: skipping one must leave both accepted state variables unchanged. State is observable when an exception occurs, so a streaming consumer must decide whether a failure leaves a partial result or cancels the operation.

Do not conflate zero with missingness. Zero can be a valid measured amount; None can represent an absent measurement. A truthiness filter removes both and changes the denominator of a mean. This is a specification error even if the loop terminates and every arithmetic operation is legal.

Worked problem

Process [1200, None, 0, -200, 500]. None is missing; negative values are valid refunds. Return count, total and mean of present records.

Trace the complete solution
  1. After 1200 the state is count 1, total 1200. Missing None leaves the state unchanged.

  2. Zero is present, giving count 2 and total 1200. The refund gives count 3 and total 1000. The final amount gives count 4 and total 1500.

  3. The mean is 1500 / 4 = 375 cents. Filtering with if amount would exclude zero and incorrectly report 500 cents over three records.

  4. An empty or all-missing stream has count zero and no defined arithmetic mean. Return an explicit absence or a documented error; do not invent a zero mean.

Independent transfer problem

The policy changes: refunds must be reported separately while the sales mean excludes refunds but includes zero. Trace the same input and state the revised invariant.

Compare the reasoning and result

Maintain sales_count, sales_total and refunds_total. The sales are 1200, 0 and 500: count 3, total 1700, mean 566⅔ cents. Refunds total −200 cents, so net remains 1500. After each prefix, sales_total sums nonnegative present amounts and refunds_total sums negative present amounts. A single net mean would erase the distinction the new report requires.

Open the unit and assigned readings →

Collections, identity and aliasing

A collection design encodes identity. Equal field values do not prove that two transactions are the same transaction. Deduplicating by an identifier can be valid only if the identifier contract and conflict rule are explicit. A second issue is aliasing: two names may point to the same mutable list. Copying an outer dictionary does not necessarily copy the lists inside it.

State the expected operation before choosing a list, set or mapping. A list preserves order and multiplicity. A set retains distinct values. A mapping associates a key with its current value; storing several events per customer requires a collection as that value. Mutation tests should check both returned values and whether input data changed unexpectedly.

Worked problem

Transactions are (id 1, Ada, 500), (id 2, Ada, 500), and a retry of (id 1, Ada, 500). Compute customer totals under an event-ID deduplication contract. Then process (id 1, Ada, 700).

Trace the complete solution
  1. IDs 1 and 2 are different events despite equal amounts. The retry of ID 1 is the same event, leaving Ada at 1000 cents.

  2. Keep a mapping from event ID to the accepted payload. A seen-ID set alone can detect repetition but cannot distinguish an identical retry from a conflicting reuse.

  3. The changed ID 1 payload is a conflict. Reject or quarantine it under a documented correction procedure; silently ignoring it conceals a discrepancy, while adding it double counts.

  4. If producing grouped lists, use a new list per key. Sharing one list among customers would allow one customer’s append to alter another customer’s history.

Independent transfer problem

A correction event ID 3 reverses event 1 for −500 and replacement event ID 4 adds 700. Show Ada’s net and explain why preserving events aids reconciliation.

Compare the reasoning and result

The accepted ledger is +500, +500, −500, +700, totaling 1200 cents. Event IDs 3 and 4 document correction rather than rewriting history. A repeated delivery of either correction ID must also be idempotent. Reconciliation can now trace the original amount, its reversal, and the replacement; a final dictionary total alone cannot explain the change.

Open the unit and assigned readings →

Parsing, validation and atomic export

Parsing asks whether bytes conform to a representation. Validation asks whether the represented record satisfies the domain contract. A syntactically valid CSV row can still contain an unknown customer or an invalid amount. Report the location and rule violated without leaking unrelated records.

Atomicity is a separate property. Writing each row directly to a destination while parsing can leave a partial export when a later row fails. For a modest file, validate all rows before writing. For larger data, write a temporary file, flush and close it, and replace the destination only after success. The precise durability guarantees depend on the filesystem; a successful rename should not be described as a complete backup or distributed transaction.

Worked problem

A CSV export has three valid records followed by an amount field containing twelve dollars. The destination already contains yesterday’s valid report. Design failure behavior that preserves it.

Trace the complete solution
  1. Use the CSV parser for quoting and column boundaries. The invalid amount can be identified as a numeric/domain conversion failure at its actual row, rather than a CSV quoting failure.

  2. Do not truncate yesterday’s file before validation. Either accumulate validated records or direct output to a separate temporary path.

  3. If conversion fails, discard the temporary output and return a useful error. Yesterday’s report remains the published destination.

  4. On success, close the output and replace the destination through the platform’s documented mechanism. Test the failure path explicitly, not only the happy path.

Independent transfer problem

A file has ten million rows, so keeping every record in memory is impractical. Propose a bounded-memory design and identify one failure that atomic replacement does not solve.

Compare the reasoning and result

Stream parsed, validated rows into a temporary output while retaining only counters and a small error sample. Commit the output after the complete input validates, or use an explicit partial-acceptance report if that is the chosen contract. Atomic replacement does not prove the input was complete, protect against a corrupted backup, or coordinate concurrent writers. Add a run identifier and a policy for writer ownership or version conflicts.

Open the unit and assigned readings →

Tests as discriminating evidence

A useful test distinguishes a correct implementation from a plausible wrong one. Repeating the implementation’s own formula in the expected-value expression can reproduce its mistake. Hand-compute a small example and choose cases at policy boundaries. Properties connect many inputs but still require assumptions: additivity applies to unrounded integer-cent sums, whereas independently rounded discounts need not be additive.

A test suite is evidence about specified behavior, not proof that no defect exists. Include invalid types, empty data, repeated events, conflicting IDs and failures during output. Separate pure-function tests from integration tests that establish whether the actual parser, coordinator and writer are connected correctly.

Worked problem

A programmer tests a total function only with [100, 200]. It passes, but the implementation first converts the list to a set. Design the smallest useful counterexample and an independent expected value.

Trace the complete solution
  1. The original test contains no duplicates, so set conversion preserves its sum. It cannot discriminate the erroneous behavior.

  2. Use [100, 100]. Two separate transactions sum to 200 cents; the set-based implementation returns 100.

  3. Add [100, −100] to test cancellation, [] to test the identity, and [0] to test whether zero is accepted without being confused with absence.

  4. For validated lists a and b, total(a + b) = total(a) + total(b). Test this property only for the unrounded total, not for a process with invoice-level rounding at each call.

Independent transfer problem

A test for a 50% invoice discount claims discounted(a+b) always equals discounted(a)+discounted(b). Use a=[1] cent and b=[1] cent with half-up rounding to evaluate that claim.

Compare the reasoning and result

One combined 2-cent invoice discounts to 1 cent. Each separate 1-cent invoice discounts to 0.5 cent and rounds to 1 cent, so their sum is 2 cents. The failed property exposes an invalid test assumption, not necessarily a defective discount function. Replace it with properties matching the chosen rounding boundary, and keep examples that verify both combined and separate invoices.

Open the unit and assigned readings →

A reproducible command-line pipeline

An integrated program should make data flow and failure behavior visible. The entry point reads configuration and arguments, calls parsing and validation, computes the result, and exports a documented format. Pure functions should not silently depend on the current working directory or print intermediate output. A command-line program can return an exit status while a reusable function returns a structured result.

Reproducibility requires more than setting a random seed. Record the input version, program version, policy choices and dependencies. Avoid including unnecessary personal data in diagnostics. A run identifier can connect a summary to its source without embedding the entire source file in logs.

Worked problem

Design a work-order estimator that can be imported in a test, run from a terminal, and retried after export failure without charging a customer twice.

Trace the complete solution
  1. Keep estimate(records, policy) pure: it returns totals and validation findings without performing payments or printing.

  2. Put argument parsing and process exit behavior behind the script entry-point guard. Importing the module must not launch a run.

  3. Write a result manifest with input checksum, policy identifier, output format and program version. Export retry is a separate operation from any payment workflow.

  4. If a payment action is later added, use a stable operation key and durable action ledger. Rerunning a calculation does not itself establish idempotent payment behavior.

Independent transfer problem

A run succeeds on one machine but reads a different rates.csv on another. Explain the likely dependency and redesign the invocation so the discrepancy is diagnosable.

Compare the reasoning and result

A relative filename may have resolved against different working directories. Require an explicit input path or a documented configuration root, resolve and report the chosen source, and include its checksum in the manifest. Keep the report free of unnecessary confidential paths if shared publicly. Tests should run from a temporary working directory to reveal hidden filesystem assumptions.

Open the unit and assigned readings →

Integrated project

Build an importable and command-line estimator for a fictional service company. Accept event IDs, customer IDs and integer-cent transactions from CSV. Specify duplicate, refund and invoice-rounding policies. Produce customer and overall reconciliations plus a run manifest. A failed export must preserve the last valid report.

Evidence and evaluation criteria

  1. A hand-calculated ledger with distinct duplicate-value events, an identical retry and a conflicting-ID rejection.
  2. Explicit cents, type, missingness, refund and rounding contracts.
  3. Pure computation functions separated from input, output and terminal execution.
  4. CSV quoting, invalid row and late-file failure tests with preserved previous output.
  5. Normal, boundary and adversarial test cases with independently calculated expected results.
  6. A reproducible invocation, input checksum and documented operational limits.
Worked project approach and limitations

Use four accepted events: +500 for Ada, +500 for Ada under a distinct ID, −500 reversing the first event, and +700 replacing it. Ada reconciles to 1200 cents before any separately specified discount. An identical retry changes no total; a reused ID with changed payload is rejected. Validate representation at the parser boundary, then pass typed records to a pure accumulator. Stage output separately and replace the destination after success. Verify that importing the module creates no files. Demonstrate the failure path with an invalid last row and compare yesterday’s output byte for byte. The project establishes calculation and export behavior; it does not implement payment settlement or guarantee filesystem durability after hardware failure.

Cumulative assessment

These are new situations. Explain your choice before opening the feedback.

Problem 1

A 2,999-cent invoice receives a 20% invoice-level discount with half-up rounding. What is due?

  1. 2,399 cents
  2. 2,400 cents
  3. 2,399.2 dollars
Answer and reasoning for every option

Best answer: A

  1. Correct. 2999 × .8 = 2399.2 cents, which rounds to 2399.
  2. Incorrect. Rounding the original price before applying the discount changes the contract.
  3. Incorrect. The calculation is in cents; display conversion must occur once.

Problem 2

A mean excludes missing None but includes zero. For [0, 600, None], what is the result?

  1. 600 cents
  2. 200 cents
  3. 300 cents
Answer and reasoning for every option

Best answer: C

  1. Incorrect. That excludes the legitimate zero observation.
  2. Incorrect. That counts the missing record as a measured zero.
  3. Correct. Two present observations sum to 600; divide by two.

Problem 3

Two equal $5 transactions have different event IDs. Which treatment preserves a transaction ledger?

  1. Keep only the most recent amount per customer
  2. Retain both events
  3. Convert records to a set of customer and amount
Answer and reasoning for every option

Best answer: B

  1. Incorrect. That overwrites rather than accumulates events.
  2. Correct. Equal values do not make distinct events duplicates.
  3. Incorrect. That erases multiplicity when legitimate purchases match.

Problem 4

A retry reuses event ID 8 with a different amount. What should the deduplication boundary do?

  1. Report an identifier–payload conflict
  2. Silently accept the first amount and conceal the mismatch
  3. Add both amounts because both requests arrived
Answer and reasoning for every option

Best answer: A

  1. Correct. Idempotence requires the repeated identifier to denote the same operation.
  2. Incorrect. This hides potentially material input disagreement.
  3. Incorrect. That double counts an operation with conflicting identity.

Problem 5

An export fails on its last input row. Which design preserves the previous valid destination?

  1. Open the destination in write mode before parsing
  2. Catch the exception and label the partial file complete
  3. Write separately and replace only after successful validation
Answer and reasoning for every option

Best answer: C

  1. Incorrect. Opening in write mode can erase the previous report.
  2. Incorrect. Error handling cannot turn an incomplete result into a complete one.
  3. Correct. The existing destination is not truncated during a failed run.

Problem 6

A test for repeated transaction handling uses [40, 40]. What expected total is independent and discriminating?

  1. Any nonnegative result
  2. 80 cents, calculated from two separate events
  3. sum(set([40,40]))
Answer and reasoning for every option

Best answer: B

  1. Incorrect. That assertion is too weak to establish the required total.
  2. Correct. A deduplicating implementation returning 40 is exposed.
  3. Incorrect. This mirrors the exact defect the test should catch.

Problem 7

A list-of-lists result changes when its input is edited later. What mechanism should be investigated first?

  1. Shared references to mutable nested lists
  2. Integer arithmetic becoming approximate
  3. The presence of a return statement
Answer and reasoning for every option

Best answer: A

  1. Correct. A shallow outer copy may retain inner aliases.
  2. Incorrect. Integer arithmetic does not explain shared mutable changes.
  3. Incorrect. Returning an object does not automatically copy its internal references.

Problem 8

A parser accepts a correctly quoted negative amount, but refunds are forbidden. What failed?

  1. CSV quoting necessarily failed
  2. All negative values are invalid Python integers
  3. Domain validation
Answer and reasoning for every option

Best answer: C

  1. Incorrect. A valid negative number is not a quoting error.
  2. Incorrect. Negative integers are valid representations.
  3. Correct. The syntax can be valid while the policy is violated.

Problem 9

Importing an estimator unexpectedly writes a report. Which change addresses the execution boundary?

  1. Remove tests
  2. Move run behavior behind an explicit entry point
  3. Rename all variables
Answer and reasoning for every option

Best answer: B

  1. Incorrect. Tests expose this behavior rather than causing it.
  2. Correct. Reusable definitions should not perform the terminal workflow at import.
  3. Incorrect. Names do not prevent top-level side effects.

Problem 10

One calculation is performed twice, then two payments are sent. Which conclusion is warranted?

  1. Calculation purity did not provide payment idempotence
  2. A deterministic calculation guarantees one external effect
  3. A local Python variable proves payments cannot repeat
Answer and reasoning for every option

Best answer: A

  1. Correct. External effects require durable operation identity and workflow controls.
  2. Incorrect. Determinism does not prevent repeated network actions.
  3. Incorrect. Local state can be lost or bypassed across processes.

Problem 11

A refund reverses an already rounded invoice. Which rule should be specified?

  1. Always add 50 before flooring any signed value
  2. Round every intermediate quantity until totals match
  3. Whether to reverse the recorded amount or round a new computation
Answer and reasoning for every option

Best answer: C

  1. Incorrect. That nonnegative formula does not define symmetric negative rounding.
  2. Incorrect. Changing intermediate rounding to force agreement conceals the policy difference.
  3. Correct. These policies can differ and must be explicit.

Problem 12

Two runs disagree after reading files with the same basename. Which manifest evidence best helps identify the discrepancy?

  1. Only the total number of Python files
  2. Resolved input identity and content checksum
  3. The screen color used by the terminal
Answer and reasoning for every option

Best answer: B

  1. Incorrect. That does not establish which rates or records were used.
  2. Correct. The basename alone does not establish that the bytes matched.
  3. Incorrect. It does not identify the actual input data.

Assigned sources