Chapter DPython only what you needPage 2 of 8

Python only what you need

Set up interfaces and contracts

Small python programs become manageable when values have clear names, repeated decisions live in functions, and collections are processed one item at a time.

~12 minSetup

Before you start

Why this matters

Before running anything, predict one observable result from the case: three model scores must be labeled with one threshold and summarized without copying the decision three times. Write the prediction beside the command or code line that should cause it. This makes the session an experiment rather than a transcription exercise.

1Learn the idea

Read

Setup the chapter step

The required setup is: Python 3 is available and the learner can run python scores.py from the directory containing the file. Confirm it before copying code. The contract separates input from output: a list of numeric scores and a threshold between zero and one goes in, and deterministic labels and a positive-count summary comes out. If either side is ambiguous, later debugging will chase the wrong layer.

The input contract is a list of numeric scores and a threshold between zero and one. The visible result is deterministic labels and a positive-count summary.

Read

Run the working example

scores = [0.2, 0.9, 0.4]
threshold = 0.5

def label(score):
    return "yes" if score >= threshold else "no"

labels = [label(score) for score in scores]
for score, result in zip(scores, labels):
    print(f"{score:.1f} -> {result}")
print("positive:", labels.count("yes"))

Expected evidence:

0.2 -> no
0.9 -> yes
0.4 -> no
positive: 1

The output may include version-specific details such as hashes, paths, fitted thresholds, or final decimal places. Compare the structural facts described here rather than copying placeholders. If the structure differs, stop and inspect the earliest unexpected line.

Read

Read it line by line

  1. scores is a list, so order is retained and every value can be visited.
  2. label has one parameter and one return value, making the threshold rule reusable.
  3. the list comprehension calls the function once per score.
  4. zip pairs corresponding values; the final count examines the labels already produced.

These lines form one chain: a list of numeric scores and a threshold between zero and one becomes deterministic labels and a positive-count summary. Change only one input first. When several values change together, you cannot tell which change caused the new behavior.

Read

Common errors and fixes

  • First failure: IndentationError points to a block whose spaces do not line up; use four spaces under def and for. Re-run the smallest command that proves the repair.
  • Second failure: NameError means a name was misspelled or used before assignment. Preserve the failing input as a test when it represents a realistic mistake.
  • Misleading success: TypeError during comparison often means a score is text such as '0.9'; convert or reject it at the input boundary. A clean-looking final line cannot cancel contradictory intermediate evidence.

When debugging, copy the exact error text and inspect names, paths, shapes, types, and versions. Explain the cause in one sentence before changing code. That discipline prevents a guessed repair from creating a second defect.

Read

Evidence for this stage

Keep the script readable: descriptive names, one purpose per function, and no hidden global mutation. Do not use eval to turn user text into Python values.

For the current setup step, save the smallest useful evidence: the relevant command, its output, and the input that produced it. Do not use a screenshot as the only record when text can be copied and searched. Keep generated artifacts separate from source inputs so rerunning the example does not destroy the evidence it is meant to evaluate.

Read every command or statement before running it. The examples deliberately expose intermediate state so a surprising result has somewhere concrete to point.

Read

Reflect on the result

Return to your opening prediction. Mark it correct or rewrite it with the condition you missed. Then explain the difference between a successful execution and a trustworthy result for this specific example.

Checking tutor…

Continue learning · glossary & guides
  1. Which line or command establishes the current step's most important fact?
  2. What output would reveal that NameError means a name was misspelled or used before assignment?
  3. Can a new user reproduce a runnable scores.py that prints each score, its label, and the number of positive predictions from the stated setup?