Chapter DPython only what you needPage 3 of 8

Python only what you need

Implement the happy path

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 minHappy path

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

Build the chapter step

Build the complete path once without adding optional features. Enter the example exactly, predict the expected output, run it, and compare. Then change one meaningful value connected to three model scores must be labeled with one threshold and summarized without copying the decision three times and explain why the result should change.

The deliverable for this step is a runnable scores.py that prints each score, its label, and the number of positive predictions.

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

Include the Python version, the run command, and one expected output in the README. Another learner should be able to change only scores and threshold without editing the labeling algorithm.

For the current build 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.

Keep the example small enough to inspect manually. Small does not mean careless: boundary values, file locations, feature order, and held-out data still determine whether the result means what you claim.

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 TypeError during comparison often means a score is text such as '0.9'?
  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?