Programming & Python · Lesson 06
Functions
Est. 30–40 min
Try it · Python in your browser
Run this lesson's example (helpers_fn.py), change a number, run it again.
Why
Why reusable helpers keep robot code sane
By the end you will write functions with typed thinking, keep side effects obvious, and clamp unsafe UI degrees before converting to radians.
Concept
The big idea: clear inputs, clear outputs
def name(args):defines;returnsends a value back.- Prefer pure helpers for math (same inputs → same outputs).
- Default args:
lo_deg=-90for common lab limits. - Docstrings: one line saying what and units.
How it works
How it actually works, step by step
Spot repeated logic
Conversions, clamps, packet builders.
Name the contract
Inputs, outputs, units.
Implement + return
No hidden globals if you can avoid them.
Test three calls
Low, mid, high — including out-of-range UI.
Visual
Visualise it: command console
Think of each console command as a function call with arguments.
Interactive · Robot command console
Commands (Python-like): drive_forward(cm=20) turn_left(deg=90) turn_right(deg=90) stop() status()
- # robot console ready — type a command
Code lab
Code lab: helpers
#!/usr/bin/env python3
"""Reusable helpers with clear inputs/outputs."""
def deg2rad(deg: float) -> float:
return deg * 3.141592653589793 / 180.0
def clamp(x: float, lo: float, hi: float) -> float:
if x < lo:
return lo
if x > hi:
return hi
return x
def joint_cmd(deg: float, lo_deg: float = -90.0, hi_deg: float = 90.0) -> float:
"""UI degrees → safe internal radians."""
safe_deg = clamp(deg, lo_deg, hi_deg)
return deg2rad(safe_deg)
for ui in [-120.0, 0.0, 45.0, 200.0]:
rad = joint_cmd(ui)
print(f"UI {ui:7.1f}° → internal {rad:.4f} rad")Expected output
UI -120.0° → internal -1.5708 rad UI 0.0° → internal 0.0000 rad UI 45.0° → internal 0.7854 rad UI 200.0° → internal 1.5708 rad
Real world
Where functions show up in the lab
- Unit converters at UI boundaries.
- Validation helpers before send.
- Testable pure functions in CI.
Mistakes
Common mistakes and confusions
Hardware & safety
Hardware lab and safety notes
Functions are your safety rails. A good joint_cmd() clamps every angle before it reaches a servo, so no typo can slam the horn into its end stop.
- A typical hobby servo turns about 0–180°; many arms limit each joint further (e.g. −90° to +90°).
- Put limits in one function and call it everywhere.
- Test with silly inputs (−120°, 200°) on screen first — never on the real arm.

Debugging
Debugging: when it doesn’t work
| Symptom | Likely cause | Fix |
|---|---|---|
Result is None and later math fails | Function forgot return | Return the value |
| Clamp lets 200° through | lo and hi swapped | Call clamp(x, lo, hi) in that order |
| List grows between calls | Mutable default def f(buf=[]) | Use buf=None and create inside |
| Radians look like degrees (e.g. 45.0) | deg2rad() not called | Convert at the boundary, once |
Think
Think about it
Think
Why clamp degrees before converting to radians?
Experiment
Try it in the lab: extract functions
Experiment
Extract functions
- Run helpers_fn.py; confirm −120° and 200° clamp to ±90° → ±π/2.
- Add a rad2deg helper and print a round-trip.
- Call joint_cmd from a tiny loop of UI values.
Interactive · Robot command console
Commands (Python-like): drive_forward(cm=20) turn_left(deg=90) turn_right(deg=90) stop() status()
- # robot console ready — type a command
Knowledge check
Check your understanding
Knowledge check
1. def introduces…
2. In the lab, UI −120° became about…
3. A pure helper should…
4. Default arguments are written…
5. Missing return yields…
Practice quiz
Coding practice
Mini assignment
Hands-on assignment
Mini assignment
API stub
Write clamp, deg2rad, and a joint_cmd that documents units in a docstring.
Deliverables
- helpers_custom.py
- 3 example calls with printed radians
Do this, step by step
- Run
helpers_fn.py; check −120° → −1.5708 rad and 200° → 1.5708 rad. - Change the limits to 0–180° and predict the four lines.
- Add a docstring to
clampthat states units. - Write
helpers_custom.pywithclamp,deg2rad,joint_cmdand 3 example calls.
Stuck? Hints, one at a time
- Hint 1: −120° and 200° are clamped to −90° and 90°, which are ∓π/2 = ∓1.5708 rad.
- Hint 2: With 0–180°: −120 → 0.0000, 0 → 0.0000, 45 → 0.7854, 200 → 3.1416.
- Hint 3:
math.radians()does the same asdeg2rad()— use it once you know why.
Challenges (pick by level)
- 🟢 Easy: Write
rad2deg()and checkrad2deg(deg2rad(30))gives 30. - 🟡 Medium: Make
joint_cmdprint a warning when it clamps. - 🟠 Hard: Write
joint_cmds(list_of_deg, limits)that returns a list of radians for 6 joints.
Next step
Next, Lesson 7: Lists, Tuples & Dictionaries. Related: radians in Stage 1 — Angles & Radians.
Sources
- Python docs — Defining functions
- Python docs — Default argument values
- Python docs — math.radians
- Photos: Wikimedia Commons (credits under each image).
Self-attested for now — keep artifacts in your lab notebook.
Complete
Today's goal
0 of 1 done today
Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).