Week 2 · Build: Loops, conditions and functions
Session 2 of 4 · Python with a purpose · Phase 1
Plan about 15 minutes for explanation, 30 minutes for practical work and 10–15 minutes for documentation. A longer build may continue into the next session: stop safely, commit the current state and record the next check. Desktop simulations count as software evidence; label them clearly and record physical validation separately.
Engineering challenge
Can your code express a repeatable plan while refusing invalid inputs? This session focuses on loops, conditions and functions.
Before you start
The previous week’s recorded baseline and Week 1, Improve. For later sessions this week, retain the preceding session’s files and predictions.
Equipment: Desktop Python, editor, paper and ruler; for physical work, the configured 3pi+ 2040, clear floor mat and hardware checklist. Week 3 additionally uses the separate low-voltage LED circuit described in its procedure.
For any motion, verify the stop button, short time limit and clear floor area first. Keep the wheels raised for a new device program until its commands and stop behaviour are checked. A hazard or uncertain input is a reason to stop and document, not to force the trial to finish.
Theory and mathematics
Loops, conditions and functions
A for loop repeats instructions for each item in a sequence. range(3) supplies 0, 1 and 2, not 3. Indentation tells Python which statements belong inside the loop or function. A function takes inputs and can return a result; naming its parameters makes the assumptions visible. A condition selects behaviour. Putting stop inside every planned motion step is clearer than assuming a later line will always run. On a real device, a finally block also releases motors when a program exits normally or raises an exception.
Worked example — illustrative values
If distance_m = 0.6 and duration_s = 3.0, speed is 0.2 m/s. Three 0.5-second movements take 1.5 seconds of commanded motion. A printed stop after each movement is an instruction trace; it is not a measurement of actual stopping distance.
Write the calculation in your notebook before running code. State which values you measured, which you assumed and which the program calculates. A correct numerical calculation cannot rescue an incorrect physical assumption.
Run and explain the model
The following is desktop Python, not a ready-to-run motor program. Download this week’s example, save it in your student repository and run python3 code/w02.py from the repository root. The same small model is reused across the week so you can learn it, build with it, test it and revise it.
# Desktop Python teaching example. Numerical inputs are illustrative.
def speed(distance_m, duration_s):
if duration_s <= 0:
raise ValueError("duration_s must be positive")
return distance_m / duration_s
for trial in range(3):
print(trial + 1, "forward", speed(0.6, 3.0), "m/s")
print("stop")
assert abs(speed(0.6, 3.0) - 0.2) < 1e-9
Run the example on desktop Python before adapting it. Change one valid input and check the result; keep device-only calls in a separate adapter. If an exception appears, read its final line, identify the input or assumption that caused it and make the smallest explained correction. Do not delete validation merely to obtain output.
Understanding the model and its limits
Read the function from top to bottom. def speed(...) names two inputs; the indented body rejects a nonpositive time before division. return sends the numerical result back to its caller. The three-pass loop supplies trial indices 0, 1 and 2; printing trial + 1 gives human-readable labels 1, 2 and 3. The final assertion compares an approximate float within a tiny tolerance instead of requiring exact binary equality. Change one argument at a time. This example computes a speed and prints a plan; it does not measure elapsed time or communicate with motors.
Practical instructions
- Write a function plan_move(action, duration_s) that rejects negative durations and prints the action followed by stop.
- Build a list with forward, left and forward actions and loop over it.
- Keep this a desktop dry run; represent turning as text rather than importing device libraries.
- Use the official display example to show one planned action on the robot without enabling motors.
Experiment
Change only sequence length from one to three to five actions. Verify that each action has one explicit stop record.
Before testing, record your prediction, changed factor, measured response, fixed conditions and stopping rule. Save every attempted run, including failures, with a condition and source version. If hardware is unavailable, use an explicitly labelled synthetic/replay dataset and list the physical question it cannot answer. Do not invent completed trials.
Deliverable
A three-action plan with a bounded loop and explicit stops; explain the role of each function and list.
Save notebook/w02-s2.md, the relevant code revision, raw CSV or test-case records, and one labelled diagram/plot/table. Link the files relatively from your notebook. Use the entry template and report guide.
Completion criteria
- Explain loops, conditions and functions in your own words using this session’s example and its units/assumptions.
- Produce the specific evidence above: A three-action plan with a bounded loop and explicit stops; explain the role of each function and list.
- Keep predictions and raw outcomes, distinguish observations from interpretation, and explain one limitation or unresolved failure.
- Review the Git diff, commit the session’s intended files and state the next experiment or safe continuation point.
A documented failed prediction can meet the learning criteria. A missing physical trial must remain marked untested; software success alone does not validate the robot.
Reading and video
- Focused reading: Python tutorial: control flow. Study task: Find a for loop and a function; explain the indentation and returned value.
- Video/lecture option: CS50 Python: loops. Study task: Pause on a loop and predict its output before continuing. Watch a relevant 5–10 minute excerpt or use the linked notes if video is inaccessible. This is supporting conceptual material; hardware in a demonstration may differ from yours.
- Practical reference: Engineering handbook and hardware setup. Manufacturer/API references and video metadata were checked on 2026-10-09; recheck the actual firmware before transferring code.
Reflection and next step
Which assumption most affected your result? Point to one observation that supports your explanation and one alternative explanation the evidence has not ruled out. Write a specific next test with a changed factor and measurable outcome, then proceed through the week’s Learn → Build → Experiment → Improve cycle.