Lawfare Group → Knowledge Institute → Lawfare Academy
← CS 101 — Programming Foundations with Python
Weeks 1–2
Values, names, types and a precise specification
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.
Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.
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 reasoning 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.
Extended teaching and laboratory
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.
Step-by-step 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.
- 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.
- 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.
- Reject invalid quantities before computing the invoice. Format cents as dollars only at the display boundary. Record the rounding policy in tests and documentation.
From an expression to a reproducible program
Start with a small experiment before the invoice calculation. Open an installed Python 3 interpreter and enter 6250 * 3. Its interactive prompt displays 18750. In a saved file named estimate_demo.py, the same expression alone produces no displayed output: the interpreter evaluates the expression, but the script has no instruction to display it. Write print(6250 * 3), save, and run the file with the Python command available on your system, for example python3 estimate_demo.py. Do not type the >>> prompt into the file. Record the actual interpreter version with python3 --version, or the equivalent command you use. The numerical examples here do not require one particular editor.
Now execute these four assignments in order: rate_cents = 6250; hours = 3; total_cents = rate_cents * hours; hours = 4. After the third assignment the names refer to 6250, 3 and 18750. The fourth changes hours to 4, while total_cents still refers to 18750. Re-evaluating rate_cents * hours would yield 25000, but merely changing a name does not re-run an earlier expression. A trace must record values after each statement, rather than drawing an arrow from total to a permanently active formula. An expression produces a value; assignment binds its result to a name.
Types help explain another failure. Text returned by input is a string, so '6250' * 3 repeats four-character text three times. It does not yield a monetary total. Converting '6250' to an integer is appropriate only after deciding that the text denotes cents. The text '62.50' denotes dollars under a different contract. Trying int('62.50') raises ValueError; converting through float and then int can silently truncate or introduce a representation error. A parser should implement the accepted notation and units directly.
A boundary contract that can be tested
For the accompanying laboratory, a dollar input consists of an optional + or - sign, one through twelve ASCII whole-number digits, and an optional decimal point followed by one or two digits. Ordinary spaces may surround it. The complete incoming string may contain at most 32 characters. Examples are '19.95', '+19.9', '19' and '-0.05'. A missing whole-number part, exponent notation, currency symbols, commas, underscores, tabs, nonfinite values and more than two fractional digits are rejected. These are deliberate application rules; Python's numerical constructors accept a wider language. Another product could make different choices, but its choices need their own tests.
Parsing '19.9' first identifies sign, whole digits 19 and fractional digits 9. Pad the fraction on the right to 90 hundredths; 100 * 19 + 90 gives 1990 cents. Parsing '-0.05' gives magnitude 5 and then applies the negative sign, yielding -5. Do not strip the decimal point and interpret the remaining digits without accounting for their positions: that would turn '19.9' into 199 cents. Validate before adding anything to a running total. Converting malformed text to zero would fabricate a legitimate transaction.
Display is a different transformation. For -5 cents, take the absolute magnitude, divide it into whole dollars and a remainder, pad the remainder to two digits, then add the sign: -$0.05. Applying floor division directly to a negative amount gives a different decomposition. For Python integers, -7 // 4 is -2 and -7 % 4 is 1, so (-2)*4 + 1 reconstructs -7. In contrast, int(-7 / 4) is -1 because conversion truncates toward zero. Neither operation is a general instruction to round to the nearest integer.
Derive the rounding rule before implementing it
Suppose an exact result is the signed rational number N/D cents with positive integer D. Divide abs(N) by D to obtain quotient q and remainder r. The magnitude lies q + r/D cents from zero. If 2r < D, q is closer; if 2r > D, q+1 is closer. At equality our chosen rule takes the value farther from zero. Restore the original sign after this decision. This proves the rule implemented by round_ratio, including negative inputs. It also shows why adding 50 and flooring a signed numerator divided by 100 is not a symmetric extension of the earlier nonnegative formula.
For a five-cent charge discounted by 50%, N=250 and D=100. Quotient 2 and remainder 50 yield 3 cents under the tie rule. For an independently calculated five-cent credit, N=-250 gives -3 cents. The shortcut (-250+50)//100 instead yields -2, violating the stated symmetry. For a refund of a recorded invoice, first decide whether to reverse its recorded payable amount or calculate a new discounted credit. Arithmetic cannot choose the refund policy.
Decimal arithmetic also has a contract. Decimal('0.1') starts with the exact decimal tenth, while Decimal(0.1) converts the binary floating-point value already supplied. Decimal construction can preserve more digits than the current context precision; arithmetic results may then be rounded to that precision. Quantize supplies a target exponent and a rounding choice, while an Inexact trap can detect disallowed loss of nonzero digits. Decimal does not remove precision, input-validation or rounding-policy decisions. The laboratory tests those distinctions without using Decimal as the implementation of its integer-cent calculations.
Allocation is a conservation problem
To distribute 1000 cents equally over three positions, integer division gives a base share of 333 and one remaining cent. Give one extra cent to the earliest position under a declared stable ordering: [334,333,333]. The sum is exactly 1000 and the largest and smallest shares differ by at most one. For any nonnegative T and positive n, write T=nq+r with 0≤r<n. Giving q+1 to r positions and q to the others sums to r(q+1)+(n-r)q=nq+r=T. For a signed credit, allocate its magnitude and negate every share. This preserves both the total and reversal symmetry. Repeated allocations may favor early positions; rotating the order is a separate fairness policy that must be specified if required.
The original three-visit invoice pays 5387 cents after its invoice-level discount. Refunding each visit independently at 1796 cents would return 5388 cents across three refunds. Allocating the recorded payable amount instead gives [1796,1796,1795], whose sum reverses exactly the amount paid. Do not conceal the discrepancy by changing one result without recording the allocation rule.
Reading the assigned sources with a current interpreter
Read both complete beginner chapters, including their exercises, then the three complete Python tutorial chapters and the Decimal reference. Use the beginner chapters for explanation and the documentation for precise behavior. The older beginner edition illustrates PyScripter and contains a historical keyword list with exec. This course does not require that editor. In current Python 3, exec is a built-in function, while keyword.iskeyword('exec') is false; query keyword.kwlist on your own interpreter instead of treating the old list as current. Avoid naming a variable exec because that hides the built-in name. The Decimal reference also distinguishes Decimal's truncating // from integer floor division; choose the numeric type before transferring an arithmetic identity to code. The laboratory uses Python integers for the derived quotient/remainder algorithms.
Independent progression
First, trace rate_cents = 1250; hours = 2; saved = rate_cents * hours; hours = hours + 1. State both saved and the freshly evaluated product, and classify '1250' * 2. Next, predict parse_cents('+7.4'), format_cents(-7), and rejection of '7.400'. Then compute signed half-away-from-zero rounding for 249/100, 250/100 and -250/100 cents. Finally allocate two cents over five positions and allocate the recorded payable 5387 cents over three refundable visits. Supply a sum proof and a test that would expose independent per-item rounding. Attempt these before opening the companion's reasoning; no submission or quiz is required.
Apply the idea
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.
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.
Further independent progression — complete record
First, trace rate_cents = 1250; hours = 2; saved = rate_cents * hours; hours = hours + 1. State both saved and the freshly evaluated product, and classify '1250' * 2. Next, predict parse_cents('+7.4'), format_cents(-7), and rejection of '7.400'. Then compute signed half-away-from-zero rounding for 249/100, 250/100 and -250/100 cents. Finally allocate two cents over five positions and allocate the recorded payable 5387 cents over three refundable visits. Supply a sum proof and a test that would expose independent per-item rounding. Attempt these before opening the companion's reasoning; no submission or quiz is required.
Read the worked reasoning
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.
Further independent reasoning
After the first three assignments, saved is 2500 cents. The last assignment changes hours to 3, leaving saved at 2500; the newly evaluated product is 3750. The string operation produces the text 12501250, not 2500. If saved changes automatically in your trace, you are treating assignment as a live equation. If the string is added numerically, you have omitted conversion and its units.
The parser returns 740 cents for +7.4 because the one fractional digit denotes tenths of a dollar, or 40 cents. Displaying -7 cents yields -$0.07. Input 7.400 is rejected under this deliberately narrow syntax even though its mathematical value could be represented exactly; lexical policy and numeric equality answer different questions. To permit extra trailing zeroes, change the contract and tests explicitly.
249/100 gives 2 because the remainder 49 is below half the denominator. 250/100 gives 3 because the exact tie goes away from zero. -250/100 gives -3 by applying the same magnitude calculation and restoring the sign. A result of -2 identifies the invalid signed use of the old add-50 shortcut.
Two cents over five positions give [1,1,0,0,0]. Shares for 5387 cents over three visits are [1796,1796,1795], and refund shares are their negatives. A test must check both the total and a maximum spread of one, rather than accepting any three numbers with the correct sum. Three independent refunds of 1796 fail conservation by one cent. The stable earliest-position tie rule is part of this implementation; it is not a claim that the order is fair for every repeated allocation.
Check understanding
Why keep the result in cents until display?
- It makes these whole-cent calculations exact
Feedback
Integer arithmetic is exact for this whole-cent contract.
- It removes every possible monetary rounding decision
Feedback
Fractional cents and allocation still require rounding rules.
- It turns strings into numbers automatically
Feedback
Conversion and validation remain explicit boundary operations.
Further reading
Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.
Use the original worked investigations and optional changed-record models in this unit. Historical directions below are retained as source history and do not require publisher chapters.
- Learning with Python 3 — Way Of The Program
- Learning with Python 3 — Variables Expressions Statements
- 1. Whetting Your Appetite
- 2. Using the Python Interpreter
- 3. An Informal Introduction to Python
- decimal — Decimal fixed-point and floating-point arithmetic
- Original Academy — names, exact money, signed rounding and allocation