Stage 02 · Lesson 04/15

Programming & Python · Lesson 04

Conditions & Decision Making

Est. 35–45 min

Try it · Python in your browser

Run this lesson's example (threshold_policy.py), change a number, run it again.

Why

Why robots need clear if/elif/else policies

By the end you will write ordered threshold policies, put battery abort first, and test edge cases on paper.

Concept

The big idea: branch on sensor truth

  • if condition: runs a block when condition is true.
  • elif chains more tests; first match wins.
  • else catches the remaining cases.
  • Order matters: check ABORT / STOP before CRUISE.
  • Prefer named constants: STOP_CM = 15.

How it works

How it actually works, step by step

  1. List outcomes

    ABORT, STOP, SLOW, CRUISE — name them.

  2. Order hazards first

    Battery fail and collision stop before “go fast”.

  3. Write comparisons

    distance_cm < 15, battery_ok is False, etc.

  4. Table-test

    Pick 4 input rows; predict outputs; run the script.

Visual

Visualise it: code-flow decisions

Step through if / if-else / while style flow. Change the condition and watch the path highlight.

Interactive · Code flow visualizer

distance = sensor.read()
if distance < 20:
    stop()
    turn_left()
else:
    drive_forward()
  1. 01 · read sensor
  2. 02 · else → drive_forward()
  3. 03 · done

Worked example

Worked example: four cases

Policy table
distance_cmbattery_okcommand
10TrueSTOP
25TrueSLOW
55TrueCRUISE
25FalseABORT

Code lab

Code lab: threshold policy

threshold_policy.py · Python
#!/usr/bin/env python3
"""Water-tank / parking-sensor style threshold policy."""

def policy(distance_cm: float, battery_ok: bool) -> str:
    if not battery_ok:
        return "ABORT"
    if distance_cm < 15:
        return "STOP"
    elif distance_cm < 40:
        return "SLOW"
    else:
        return "CRUISE"

cases = [
    (10.0, True),
    (25.0, True),
    (55.0, True),
    (25.0, False),
]
for d, bat in cases:
    print(f"distance_cm={d:4.1f} battery_ok={bat!s:5} → {policy(d, bat)}")

Expected output

distance_cm=10.0 battery_ok=True  → STOP
distance_cm=25.0 battery_ok=True  → SLOW
distance_cm=55.0 battery_ok=True  → CRUISE
distance_cm=25.0 battery_ok=False → ABORT

Real world

Where thresholds live in the lab

  • E-stop software latch: if estop → disable PWM.
  • Workspace limits: if joint out of range → hold.
  • Mode switches: teach vs run vs fault.

Mistakes

Common mistakes and confusions

Hardware & safety

Hardware lab and safety notes

Test your policy by hand before any robot moves: hold a book in front of an HC-SR04 (or type numbers) and say aloud what the robot should do at 10, 15, 25 and 40 cm.

  • Put a ruler on the desk; mark 15 cm and 40 cm with tape.
  • Edge cases matter: at exactly 15 cm the code says SLOW (because < 15 is False).
  • Battery check goes first — a dead battery beats every other rule.
HC-SR04 ultrasonic sensor module
HC-SR04 ultrasonic sensor — feed its distance into policy() to test your bands.Photo: SparkFun Electronics · CC BY 2.0 · Source: Wikimedia Commons · resized, converted to WebP

Debugging

Debugging: when it doesn’t work

Symptom → likely cause → fix
SymptomLikely causeFix
SyntaxError on if d = 10:= instead of ==Use == (or <) for comparison
Robot never stopsCRUISE checked before STOPOrder checks: hazards first
At 15 cm the result is SLOW, not STOP< excludes the boundaryUse <= if 15 cm should stop
battery_ok is the string "False" and still passesNon-empty strings are truthyConvert to a real bool
NoteRead the last line of a Python error first — it names the problem — then the line number above it. Change one thing at a time and re-run.

Think

Think about it

Think

Why put battery_ok check before distance checks?

Experiment

Try it in the lab: threshold policy

Experiment

Threshold policy

  1. Write STOP_CM and SLOW_CM constants.
  2. Fill a 4-row table of inputs → expected commands.
  3. Run threshold_policy.py and compare.
  4. Use the code-flow interactive to trace one if-else path.

Interactive · Code flow visualizer

distance = sensor.read()
if distance < 20:
    stop()
    turn_left()
else:
    drive_forward()
  1. 01 · read sensor
  2. 02 · else → drive_forward()
  3. 03 · done

Knowledge check

Check your understanding

Knowledge check

1. First matching elif/if branch…

2. In our demo, distance 25 and battery False →

3. Comparison operator for equality is…

4. Named STOP_CM helps because…

5. else runs when…

Practice quiz

Loading practice quiz…

Coding practice

Loading coding exercises…

Mini assignment

Hands-on assignment

Mini assignment

Policy card

Design an if/elif/else policy for a desk sensor with at least one abort condition and two speed bands.

Deliverables

  • Policy card (constants + branches)
  • 4-row test table

Do this, step by step

  1. Run threshold_policy.py and check the four outputs.
  2. Add cases (15.0, True) and (40.0, True). Predict, then run.
  3. Move the battery check to the bottom and see which case breaks.
  4. Make your policy card: constants, branches, and a 4-row test table.

Stuck? Hints, one at a time

NoteTry the task first. Read one hint, try again, and only then read the next one.
  1. Hint 1: 10 → STOP, 25 → SLOW, 55 → CRUISE, battery False → ABORT.
  2. Hint 2: 15.0 → SLOW and 40.0 → CRUISE, because both comparisons are strict <.
  3. Hint 3: With battery last, (25.0, False) returns SLOW — dangerous. Hazards first.

Challenges (pick by level)

  • 🟢 Easy: Add a constant STOP_CM = 15 and use it instead of the number.
  • 🟡 Medium: Add a REVERSE band below 5 cm.
  • 🟠 Hard: Write a loop that tests all distances 0–60 cm in steps of 5 and prints the table.

Next step

Next, Lesson 5: Loops. Related: feedback thinking in Stage 7 — Control Systems & PID.

Sources

Self-attested for now — keep artifacts in your lab notebook.

Complete

Today's goal

0 of 1 done today

0-day streak
Daily goal:lessons, quizzes or assignments a day

Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).

Stuck somewhere?

Ask a doubt about this lesson

Saved with this lesson's id and your email so we can reply. Privacy · or email contact@aihubstation.in