Chapter 2 – Sensor Fusion and Coding Structures
2.2 – Repetition Code Structures
This module will teach you about using loops in Zumi’s Blockly programming language. Loops are used to repeat parts of your code, making it more efficient and concise. This tutorial will walk you through using a loop to write code for driving Zumi in a square, and then show you how to use loops to create other shapes like triangles, pentagons, hexagons, and octagons.
Step 1: Import Libraries
from zumi.zumi import Zumi
import time
zumi = Zumi()
Step 2: Shapes with Loops
Certain shapes have a set number of degrees that the internal angles add up to. For example, a square’s angles add up to 360°, while a triangle’s angles add up to 180°. For shapes that have sides of equal length, you can use loops to write more efficient code.
Step 3: Square code
To appreciate the value of a for loop, first think about the code for driving in a square. Since a square has four equal sides, you would need to go forward then turn left or right four times.
This is the code for driving in a square.
from zumi.zumi import Zumi
zumi = Zumi()
zumi.forward()
zumi.turn_left()
zumi.forward()
zumi.turn_left()
zumi.forward()
zumi.turn_left()
zumi.forward()
zumi.turn_left()
What is similar about this code?
zumi.forward() and zumi.turn_left() are repeated 4 times!
Step 4: Loops
To avoid repeating the same section of code four times, you can use a loop, which lets you repeat parts of your code.
from zumi.zumi import Zumi
zumi = Zumi()
for x in range(4):
zumi.forward()
zumi.turn_left()
The “x in range(4)” can be interpreted as “as long as x is less than 4”.
The x variable used in the for loop is automatically initialized to 0 and will increment each time until it reaches 4. So first it will run as x = 0, then x = 1, then x = 2, then x = 3, then x = 4. However, when x reaches 4, the code will not run and the loop will terminate because the loop condition has been reached and 4 is not less than 4.
Step 5: More shapes!
Using loops, you can create other shapes like triangles, pentagons, hexagons, and octagons! Remember, the number of degrees multiplied by the number of sides should be equal to 360 degrees.
Activity
Code Zumi to move in a triangle.
Hint
: Import libraries, create Zumi object and use a for loop to simplify the triangle movement. Use this picture to think of the angle to turn at. Use the turn_right() function.
Step 6: Review
In this lesson, you learned how to use for loops to make your code more efficient and solve repeated code.
Demo Video
Questions