Lawfare Academy

CS 101 — Programming Foundations with Python · Weeks 1–2

Values, names, types and a precise specification

Full teaching sequence and cumulative subject work

Begin before the invoice example. Work the chapter exercises on syntax, values, types, assignment, expressions, input and output. Trace each variable after every statement and distinguish a syntax error from a correct execution that answers the wrong question. Then study the original assigned documentation as a language reference and complete the worked and transfer problems.

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

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 reasoning
  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 transfer solution

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.

Learning objectives

  • Explain and trace the mechanisms in values, names, types and a precise specification.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Study the mechanism

A program is a repeatable transformation of inputs into outputs under explicit rules. Before writing syntax, specify accepted inputs, output units and failure behavior. For a work-order estimate, an hourly rate might be an integer number of cents, hours a nonnegative integer, and the output a total in cents. This contract is narrower than a real payroll system, deliberately excluding overtime, taxation and fractional hours until those rules are defined.

A variable name refers to a value; assignment changes which value the name refers to. It does not state an algebraic identity that remains true forever. After total = rate * hours, changing hours does not recalculate total. Evaluate each expression using the values at that moment. Python's int and str are different types: multiplying an integer by an integer performs arithmetic, while multiplying a string by an integer repeats text. Conversion belongs at the input boundary, where invalid input can be recognized rather than silently propagated.

Integer cents make this small monetary example exact. Binary floating-point represents many decimal fractions approximately, so do not assume that a displayed decimal has an exact internal representation. Integer cents alone do not solve allocation or fractional-rate rounding; such extensions require a stated policy. Separate calculation from display: calculate 18750 cents first, then format dollars and cents for a person. A label such as rate is insufficient documentation when two contributors might interpret it as dollars and cents respectively.

Worked example

def estimate(rate_cents, hours):
    if type(rate_cents) is not int or type(hours) is not int:
        raise TypeError("Use integer cents and whole hours")
    if rate_cents < 0 or hours < 0:
        raise ValueError("Inputs must be nonnegative")
    return rate_cents * hours

assert estimate(6250, 3) == 18750

The call binds 6250 to rate_cents and 3 to hours. Both type checks pass, neither value is negative, and multiplication returns 18750. The function returns a number rather than printing it, so a caller can save, format or further analyze the result. The deliberately strict type check rejects bool, which is an int subclass in Python; this is a contract choice rather than a universal rule. Calling estimate("6250", 3) raises before arithmetic, preventing accidental string repetition.

Check your understanding

Why keep the result in cents until display?

  1. It makes these whole-cent calculations exact
  2. It removes every possible monetary rounding decision
  3. It turns strings into numbers automatically
Answer and reasoning for every option

Correct: It makes these whole-cent calculations exact Integer arithmetic is exact for this whole-cent contract.

Reconsider: It removes every possible monetary rounding decision Fractional cents and allocation still require rounding rules.

Reconsider: It turns strings into numbers automatically Conversion and validation remain explicit boundary operations.

Transfer laboratory: Currency allocation and an exact invariant

A 1000-cent discount must be split over three equal items. Design an allocation that preserves the total. Explain why independently rounding 1000/3 for every item fails.

Work through the full solution

Use integer division and distribute the remainder: base share 333 cents, remainder 1. Allocate [334,333,333] under a documented tie-breaking rule. The sum remains exactly 1000. Independent rounding to 333 loses one cent, while rounding each to 334 creates two cents. Test zero discount, one item and more items than cents; reject a nonpositive item count. This problem extends the estimator’s whole-cent contract to a decision about indivisible allocation.

Evidence of understanding

Allocation sum equals the input; shares differ by at most one cent; tie policy and invalid inputs are explicit.

Complete on-site teaching readings

These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.

  1. 1. Whetting Your Appetite · Python Software Foundation and Python documentation contributors
  2. 2. Using the Python Interpreter · Python Software Foundation and Python documentation contributors
  3. 3. An Informal Introduction to Python · Python Software Foundation and Python documentation contributors
  4. decimal — Decimal fixed-point and floating-point arithmetic · Python Software Foundation and Python documentation contributors

Open in My Learning to record progress →