Learn 3: 3-2-1-GoPiGO!

This is the first challenge within the Robotics with GoPiGo and Python Curriculum.

Your task is to program your robot to navigate an area of previously unseen terrain to reach its destination, passing through a number of waypoints.

4. Loops and Iterations

In the above code we repeated the same sequence of driveturn and sleep instructions four times: once for each side of the square. That's not very efficient, is it?

          • What if we wanted to trace out a 12 sided shape?
          • What if we then wanted to make that shape bigger or smaller?

You’ll have to edit an awful lot of code, won’t you? 

How about if we just tell our robot orienteer the sequence of actions necessary to trace one side of our shape and then instruct it to repeat those actions as many times as necessary?

NOTE:

A sequence of actions that is repeated is called a loop and each repetition of the sequence is called an iteration.

      1. Click on the Insert A Cell Below icon in your notebook to open up a third cell in your Jupyter Notebook
      2. Type the following code into it:

# repeat the following actions 4 times (once for each side of the square)

for i in range (0,4):  

    # trace the side of the square

    orienteer.drive_cm(50)

    # rotate clockwise 90 degrees

    orienteer.turn_degrees(90)

    # pause for 1 second

    time.sleep(1)


Once the code is entered (pay attention to periods and spaces!) you are ready to test it!

      1. Click the Run Selected Cells  icon to run the code in our new cell.

What do you see happening?

Note :

Indentation: Python is very fussy about indenting your code. Everything indented by the same amount is considered to be part of the same code block. In this case, it’s the set of actions that we want the robot orienteer to repeat. Try deleting the indentation on the time.sleep() instruction at the end and re-running your code. How does this change the behavior?

Go Further:

Try another shape: Now that the code is a lot shorter and more easily editable, can you change it to instruct our robot orienteer to perform a newfangled triangle dance instead?

      • How many iterations do you need?
      • What is the correct angle of rotation?