Chapter DPython only what you needPage 1 of 8

Python only what you need

Define the lab goal and success criteria

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 minLab goal

1Try it yourself

Code Lab

Python only what you need

Run the starter, then edit it. Print the number of topics.

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.

2Learn the idea

Read

Explain the chapter step

Begin by writing the success condition in observable terms. For this case, success is not familiarity with the vocabulary; it is producing a runnable scores.py that prints each score, its label, and the number of positive predictions. Record the starting state so you can distinguish an improvement from a result that was already present.

On this page, the practical job is to state a measurable outcome before changing anything. The running case is three model scores must be labeled with one threshold and summarized without copying the decision three times.

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

Check the boundary values 0.49, 0.50, and 0.51. The middle value must be yes because the operator is >=. Also verify an empty score list prints positive: 0 without crashing.

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

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.

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 IndentationError points to a block whose spaces do not line up?
  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?