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.
That's the Python you need. Next up is Pick & Place, where your program chooses which ball the arm picks up in just this way.