Step 7
Loops
Repeat work for every item in a list: add up totals and find the closest ball.
Do it for every item
A for loop runs its indented block once for each item in a list, with the loop variable set to that item:
for color in ["red", "green", "blue"]:
print(color, "ball")
To add things up, create a variable before the loop and update it inside:
total = 0
for d in [0.25, 0.5, 0.25]:
total = total + d # or: total += d
print(total) # 1.0
range(n) counts 0, 1, …, n − 1, which are exactly the indexes of a list with n items. Use it when you need the index as well as the item:
names = ["red", "green"]
for i in range(len(names)):
print(i, names[i])
The best so far
To find the smallest value, remember the best one seen so far and replace it whenever you find a better one:
best = values[0]
for v in values:
if v < best:
best = v
Robots do this constantly: the closest ball, the shortest path, the pose with the smallest error.
Your task
- Write
total(distances)so it returns the sum of a list of numbers, using a loop. An empty list adds up to 0. - Write
closest_ball(names, distances).names[i]is a ball's colour anddistances[i]is how far that ball is from the gripper. Return the name of the closest ball. If two are equally close, return the one that comes first.
Next up
That's the Python you need to start. Next is Pick & Place, where your programs drive the arm itself, and later loop over every ball on the table to clear it.
Its code uses a few things this lesson didn't cover. Here's what they mean:
from robot import arm, gripper, world, simbrings in the objects that control the simulator, the wayimport mathbrings in the math module.import numpy as npbrings in numpy. Positions and joint angles come as numpy arrays, which work like lists but also do maths on every item at once.x, y, _ = world.cup.positionunpacks a position into three variables in one line._is the usual name for a value you don't need.arm.move_joints(READY, duration=1.5)names an argument with a keyword, so it's clear what the 1.5 means.