Hi, my name is GarbageRider. I am a robot that collects garbage in the streets. I’ll need instructions to find all the garbage cans. Then we’ll also try to find all of the dumpsters and clean those up as well. We’ll need an efficient path so we can get this job done as quickly as possible!
In this lesson, you will learn about for loops. A for loop runs a set number of times. Earlier you learned about while loops. In the example below the while loop moves forward and turns right forever. The for loop will move forward and turn right, repeated three times.
In the for loop above there is an index i. The for loop runs three times so the index i will take on the values 0, 1, and 2. Notice that since we start with index i = 0, we never get to index i = 3.
Checkpoint #1 – First Collection
Checkpoint #2 – Completing the First Street
Run the simulation and examine the robot’s motion. We can represent this algorithm as shown below.
Checkpoint #3 – Completing the First Turn
Checkpoint #4 – Completing the Second Turn
Could we write a shorter code instead? Instead of repeating all of the code twice, what if we added a second for loop with a range of 2? Here is an example to help you get started.
for j in range(0,2):
for i in range(0,5):
# more of your code here
Checkpoint #5 – Collecting all the Pink Trash
Now try to modify your code so it collects all the pink and blue pickup locations. To get started, consider the path in the image below. Try to think of ways to make your code as compact as possible.