D.HOSKIA
Module 1·60 min

Python Fundamentals

Python Fundamentals

Python is the working language of robotics. ROS 2 uses it extensively, and most research and prototyping in the field happens in Python.

Variables and Types

# Numbers
position = 0.0          # float
count = 0               # int
is_homed = False        # bool

# Strings
joint_name = "hip_abduction"

# Lists
positions = [0.0, 1.2, -0.5, 0.8, 0.3, 0.1]

# Dicts
joint_state = {
    "position": 0.0,
    "velocity": 0.0,
    "effort": 0.0,
}

Functions

def clamp(value: float, min_val: float, max_val: float) -> float:
    """Clamp a value to [min_val, max_val]."""
    return max(min_val, min(max_val, value))

# Usage
safe_torque = clamp(commanded_torque, -10.0, 10.0)

NumPy Basics

NumPy arrays are the foundation of numerical robotics work — transforms, Jacobians, state vectors.

import numpy as np

# Create arrays
q = np.zeros(6)              # 6-DOF joint position vector
q = np.array([0.1, 0.2, 0.0, -0.5, 0.3, 0.0])

# Element-wise operations
q_deg = np.degrees(q)        # rad → degrees
q_rad = np.radians(q_deg)    # back to radians

# Matrix multiplication
R = np.eye(3)                # 3×3 identity (rotation matrix)
v = np.array([1.0, 0.0, 0.0])
rotated = R @ v              # @ is matrix multiply

Classes

class Joint:
    def __init__(self, name: str, min_pos: float, max_pos: float):
        self.name = name
        self.min_pos = min_pos
        self.max_pos = max_pos
        self._position = 0.0

    @property
    def position(self) -> float:
        return self._position

    @position.setter
    def position(self, value: float) -> None:
        self._position = clamp(value, self.min_pos, self.max_pos)

This pattern — a class with validated setters — is how you protect joints from out-of-range commands.