Python basics¶
MARLIN robot programs are written in Python. This section teaches the Python you need before you read the MARLIN API guide.
It does not teach MARLIN itself. It teaches the language features that MARLIN code is built from: variables, operators, data structures, loops, functions, and classes.
If you already know Python, skip this section.
These pages are a condensed subset
This section covers only the Python that MARLIN programs use, explained as simply as possible. It is not a complete or authoritative description of the language, and it leaves plenty out.
The official Python documentation is the source of truth: https://docs.python.org/3/. Start with the official tutorial when you want to go beyond what is here.
Before you start¶
You need Python 3.10 or newer and VS Code. See Install MARLIN for setup instructions.
You do not need a robot to practise. Create a plain .py file, write code in
it, and run it from the VS Code terminal:
Read the pages in this order¶
| Page | What it teaches |
|---|---|
| Variables and operators | Storing values, and the four kinds of operator |
| Data structures | Lists, tuples, and dictionaries |
| Control flow | if/elif/else, for, while, break, continue |
| Functions and scope | Reusable blocks of code, arguments, return values, imports, and variable scope |
| Classes | Objects, attributes, and methods |
Why this matters for your robot¶
Every idea in this section shows up in a real MARLIN program:
from marlin import Robot, Thruster # importing a library
robot = Robot() # creating an object
robot.configure(
sensors={}, # a dictionary
effectors={"M1": Thruster},
)
def driver(robot): # a function with an argument
while robot.running: # a while loop
power = robot.controller.joystick("ONE").value # a variable
robot.thruster("M1").set_duty(power) # a method call
robot.run(driver=driver)
Once you understand the parts above, that program stops looking like magic.
Comments¶
A # starts a comment. Python ignores everything after it on that line.
Comments are notes for humans, so use them to explain why your code does
something.
Comments appear in a different colour in VS Code, usually green.