Stage 02 · Lesson 06/15

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; return sends a value back.
  • Prefer pure helpers for math (same inputs → same outputs).
  • Default args: lo_deg=-90 for common lab limits.
  • Docstrings: one line saying what and units.

How it works

How it actually works, step by step

  1. Spot repeated logic

    Conversions, clamps, packet builders.

  2. Name the contract

    Inputs, outputs, units.

  3. Implement + return

    No hidden globals if you can avoid them.

  4. 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

helpers_fn.py · Python
#!/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.
Two small hobby servo motors
Hobby servos — clamp the angle in software before you send it.Photo: Kborer · Public domain (released by the author) · Source: Wikimedia Commons · resized, converted to WebP

Debugging

Debugging: when it doesn’t work

Symptom → likely cause → fix
SymptomLikely causeFix
Result is None and later math failsFunction forgot returnReturn the value
Clamp lets 200° throughlo and hi swappedCall clamp(x, lo, hi) in that order
List grows between callsMutable default def f(buf=[])Use buf=None and create inside
Radians look like degrees (e.g. 45.0)deg2rad() not calledConvert at the boundary, once
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 clamp degrees before converting to radians?

Experiment

Try it in the lab: extract functions

Experiment

Extract functions

  1. Run helpers_fn.py; confirm −120° and 200° clamp to ±90° → ±π/2.
  2. Add a rad2deg helper and print a round-trip.
  3. 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

Loading practice quiz…

Coding practice

Loading coding exercises…

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

  1. Run helpers_fn.py; check −120° → −1.5708 rad and 200° → 1.5708 rad.
  2. Change the limits to 0–180° and predict the four lines.
  3. Add a docstring to clamp that states units.
  4. Write helpers_custom.py with clamp, deg2rad, joint_cmd and 3 example calls.

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: −120° and 200° are clamped to −90° and 90°, which are ∓π/2 = ∓1.5708 rad.
  2. Hint 2: With 0–180°: −120 → 0.0000, 0 → 0.0000, 45 → 0.7854, 200 → 3.1416.
  3. Hint 3: math.radians() does the same as deg2rad() — use it once you know why.

Challenges (pick by level)

  • 🟢 Easy: Write rad2deg() and check rad2deg(deg2rad(30)) gives 30.
  • 🟡 Medium: Make joint_cmd print 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

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