Skip to the lesson
FixTheRobot Home / VLA / Prerequisites / M2.1

VLA · Prerequisite · Python and Deep Learning

M2.1 — Python Fundamentals

The language features needed to read and write model and data code.

  • Prerequisite module 2
  • Python and Deep Learning
  • Essential
  • About 12 minutes to read

Robot-learning code is written in Python, so reading it is the first practical skill. This lesson is not a full course. It is the short list of features that show up in nearly every training script and data loader, each with an example you can run.

Learning objectives

After this lesson, you should be able to:

  • Create variables and recognise the common types.
  • Use lists, tuples and dictionaries, and index and slice them.
  • Write loops, conditions and list comprehensions.
  • Define and call functions with default and keyword arguments.
  • Read a simple class, including __init__, self and __call__.
  • Import libraries and read a traceback.
  1. Values and types
  2. Collections: lists, tuples, dictionaries
  3. Loops and comprehensions
  4. Functions
  5. Classes and objects
  6. Imports and libraries
The path of this lesson: from single values up to the structures that model code is made of.

The one-sentence idea

Most model and data code is built from a handful of Python pieces: collections that hold data, functions that transform it, and classes that bundle the two.

If you can read these pieces, you can read most training scripts.

Why Python for robot learning

Almost all current robot-learning code is written in Python: the libraries that train models, load camera images and read demonstration datasets all expose Python interfaces. You do not need to be an expert programmer. You need to read a training script, follow where the data goes, and change a few lines with confidence.

This lesson covers the small part of the language that appears constantly in that code: values and types, collections, loops, functions, classes and imports. Every example is short and can be run as-is, and the printed results shown below were checked by running them.

Values and types

A variable is a name attached to a value. Python figures out the type from the value, and you can inspect it with type(). The types you will meet first are integers (int), decimal numbers (float), text (str) and true/false values (bool).

joint_angles = [0.10, -0.50, 1.20]   # a list of floats (radians)
gripper_open = True                  # a bool
name = "arm_1"                       # a str
print(type(joint_angles), len(joint_angles))

Output:

<class 'list'> 3

Text after # is a comment. Names are case-sensitive, and by convention are written in lower_case_with_underscores. Note that = assigns a value; to compare two values for equality, use ==.

Lists, tuples and dictionaries

Three collection types hold most of the data you will handle:

List [ ]
An ordered, changeable sequence, such as the joint angles of an arm or the frames of a video.
Tuple ( )
An ordered sequence that cannot be changed after creation, often used for fixed groups such as an (x, y, z) position or a shape.
Dictionary { }
A set of named entries. Robot observations are usually dictionaries, with keys such as "image" or "joints".
obs = {"joints": [0.1, -0.5, 1.2], "gripper": 0.8}
print(obs["joints"][1])        # the second joint: counting starts at 0
print(list(obs.keys()))

pose = (0.4, 0.0, 0.2)         # a tuple
x, y, z = pose                 # unpacking into three names
print(z)

Output:

-0.5
['joints', 'gripper']
0.2

Indexing starts at 0, so the first item is [0] and the last is [-1]. A slice such as items[1:3] takes the items from position 1 up to, but not including, position 3. This convention carries over directly to NumPy and PyTorch in the next lessons.

Loops, conditions and comprehensions

A for loop repeats a block for each item. An if statement chooses between blocks. Indentation is part of the syntax: the indented lines belong to the statement above them, normally four spaces.

angles = [0.10, -0.50, 1.20, 0.30]
for i, a in enumerate(angles):    # enumerate gives the index and the item
    if a < 0:
        print(i, "negative")
print(angles[1:3], angles[-1])

Output:

1 negative
[-0.5, 1.2] 0.3

A list comprehension builds a new list from an old one in a single line. It is very common in data code, and reads as “for each a in angles, compute 2 * a”:

angles = [0.10, -0.50, 1.20, 0.30]
doubled = [2 * a for a in angles]
big = [a for a in angles if a > 0.25]    # with a filter
print(doubled)
print(big)

Output:

[0.2, -1.0, 2.4, 0.6]
[1.2, 0.3]

Functions

A function packages a computation under a name. It takes parameters and returns a result with return. Parameters can have default values, and a caller can pass arguments by name, which makes calls easier to read.

def clip(value, low=-1.0, high=1.0):
    """Limit a value to the range [low, high]."""
    return max(low, min(high, value))

print(clip(1.7), clip(-0.3), clip(5, high=2))

Output:

1.0 -0.3 2

Functions like this are everywhere in robot code, for example to keep a commanded action inside the robot’s limits. The text in triple quotes is a docstring, a short description that documentation tools and editors display.

Classes and objects

A class bundles data and the functions that work on it. Calling the class creates an object. Inside a class, self refers to the object itself, and __init__ runs when the object is created. If a class defines __call__, its objects can be called like functions.

class Policy:
    def __init__(self, gain):
        self.gain = gain              # data stored on the object

    def __call__(self, error):
        return self.gain * error      # behaviour

policy = Policy(gain=2.0)
print(policy(0.25))                   # the object is called like a function

Output:

0.5

This pattern matters because neural-network models in PyTorch are classes: you create one with its settings in __init__, then call the object on some input to run it. Recognising that shape makes model code much easier to read.

Imports, f-strings and errors

Code from other files and libraries is brought in with import. You will begin almost every script with lines like import numpy as np and import torch; the first can be a short alias, which is why you see np. Libraries are installed with pip, normally inside a virtual environment so that each project keeps its own versions.

An f-string puts values into text: write f"..." and place expressions in braces, optionally with a format such as :.3f for three decimals.

import math
print(f"pi is about {math.pi:.3f}")

Output:

pi is about 3.142

When something goes wrong, Python prints a traceback. Read it from the bottom: the last line names the error type and message, and the lines above show where it happened. Typical errors in data code are KeyError (a missing dictionary key), IndexError (an index past the end) and TypeError (an operation on the wrong kind of value). You can handle one deliberately with try and except:

obs = {"joints": [0.1, -0.5, 1.2]}
try:
    obs["velocity"]
except KeyError as e:
    print("missing key:", e)

Output:

missing key: 'velocity'

Putting it together: reading demonstration rows

Robot demonstrations are often stored as rows of numbers, one row per time step. This example turns text rows (like lines of a CSV file) into a list of dictionaries, using only what this lesson covered:

rows = ["0.0,0.10,-0.50",
        "0.1,0.12,-0.48",
        "0.2,0.15,-0.45"]

trajectory = []
for row in rows:
    t, j1, j2 = (float(v) for v in row.split(","))   # split text, convert to numbers
    trajectory.append({"t": t, "joints": [j1, j2]})

final = trajectory[-1]
print(len(trajectory), final["joints"])

Output:

3 [0.15, -0.45]

Each row is split at the commas, the pieces are converted to float, and the result is stored as a dictionary with a time and the joint values. A later lesson on demonstrations and trajectory datasets builds on exactly this kind of structure.

Common misconceptions

Misconception 1 “I need to be a strong programmer before starting robot learning.”

Correction You need to read and make small changes to code, which this short list of features covers. Fluency grows by working with real projects.

Misconception 2 “Indentation is only style.”

Correction In Python indentation defines which lines belong to a loop, condition or function. Changing it changes the program.

Misconception 3 “= and == mean the same thing.”

Correction = assigns a value to a name, and == compares two values. Mixing them up is a common beginner error.

Misconception 4 “Index 1 is the first item.”

Correction Python counts from 0, so the first item is index 0. The same rule holds in NumPy and PyTorch.

Engineering takeaways

  1. Variables name values, and type() shows what kind of value you have.
  2. Lists and tuples are ordered, tuples cannot change, and dictionaries hold named entries.
  3. Indexing starts at 0, and a slice a:b stops before b.
  4. Indentation defines blocks in loops, conditions and functions.
  5. List comprehensions build new lists in one line.
  6. Functions take parameters, which can have defaults, and return results.
  7. A class bundles data and behaviour, and __call__ lets an object be called like a function.
  8. Read a traceback from the bottom to find the error and where it came from.

Learn the few pieces that model code is built from, and a training script stops looking like a wall of text.

Knowledge check

Try each question first, then reveal the explanation.

Question 1

What does this print? items = [10, 20, 30, 40] then print(items[1:3], items[-1])

Explanation

[20, 30] 40. The slice starts at index 1 and stops before index 3, so it holds the items at positions 1 and 2. Index -1 is the last item.

Question 2

Write a list comprehension that keeps only the positive numbers from values.

Explanation

[v for v in values if v > 0]. It reads as “for each v in values, keep v if it is greater than 0”.

Question 3

In class Policy with def __call__(self, error), what does policy(0.25) do?

Explanation

It runs the object’s __call__ method with error = 0.25. Objects that define __call__ can be used like functions. This is the same pattern used when you run a neural-network model on an input.

What’s next

You can now read the Python used in model and data code. Next is the library that makes working with arrays of numbers fast.

Next lesson

M2.2 — NumPy and data manipulation

Working with arrays, shapes and indexing.

Back to the VLA roadmap prerequisites