Skip to content

API Basics

One page, two jobs: just-enough Python syntax + a map of the SPIKE 3 modules. With Word Blocks experience, you've met every concept already.

Python crash course (Word Blocks side by side)

Word BlocksPython
set [speed] to [50]speed = 50
change [speed] by [10]speed += 10
if <...> then / elseif ...: / else:
repeat [10] timesfor i in range(10):
foreverwhile True:
repeat until <cond>while not cond:
<A> and <B> / <A> or <B>A and B / A or B
wait [1] secondsawait runloop.sleep_ms(1000)
wait until <cond>await runloop.until(cond_function)
My Block definitiondef / async def

Python uses indentation (4 spaces) for "contained inside", like blocks wrapping blocks:

python
for i in range(3):
    print(i)        # indented = inside the loop
print("done")       # not indented = after the loop

Functions can return values - the thing My Blocks can't do:

python
def is_black(port_id):
    return color_sensor.reflection(port_id) < 35

if is_black(port.C):
    ...

SPIKE 3 module map

ModuleOwnsTypical call
motorsingle motorsmotor.run_for_degrees(port.A, 360, 500)
motor_pairthe drive basemotor_pair.move_for_degrees(...)
color_sensorcolor sensorcolor_sensor.reflection(port.C)
distance_sensordistance sensordistance_sensor.distance(port.D)
force_sensorforce sensorforce_sensor.pressed(port.E)
hub packagethe hub itselffrom hub import port, motion_sensor, light_matrix, button, sound
colorcolor constantscolor.BLACK, color.RED
runloopasync runtimerunloop.run(), runloop.sleep_ms(), runloop.until()

Ports are written port.A through port.F (from from hub import port).

Unit conversion table (the biggest trap)

Python API units differ from what Word Blocks display:

QuantityWord BlocksPython
Motor speed% (0-100)degrees/second (large motor tops out ~1050)
Distancecmmm, -1 when no target
Yaw angledegreesdecidegrees (900 = 90°)
Force% or Ndecinewtons (0-100)
Timesecondsmilliseconds

Full example: drive to the black line

python
import runloop, motor_pair, color_sensor
from hub import port

motor_pair.pair(motor_pair.PAIR_1, port.A, port.E)   # left A, right E

def on_black():
    return color_sensor.reflection(port.C) < 35

async def main():
    motor_pair.move(motor_pair.PAIR_1, 0, velocity=300)   # start driving (non-blocking)
    await runloop.until(on_black)                          # wait for the condition
    motor_pair.stop(motor_pair.PAIR_1)                     # stop

runloop.run(main())

Compare with the Word Blocks version (start moving → wait until → stop moving): identical structure.

Note runloop.until() takes the function itself (on_black, no parentheses), not its result - runloop calls it repeatedly until it returns True.

Exercises

  1. Translate the Word Blocks "count 3 lines and stop" program into Python (hint: while + two runloop.until).
  2. Write read_black_white(): record the black value on the left button press, white on the right, print the suggested threshold.

Next lesson: the complete Motors & Sensors API.