Loops Save Work
A twelve-sided shape needs twenty-four commands if you type every one. With a loop it needs one line. Programmers love loops, not because they are clever, but because they are lazy in the best way.
π‘ The idea
A loop repeats work, so one line can do the job of twenty.
- repeat 6 [ ... ] does the work inside the brackets six times.
- For a shape with equal sides, the turn is 360 divided by the number of sides.
- Five sides means turns of 72, because 360 divided by 5 is 72.
- Eight sides means turns of 45. Twelve sides means turns of 30.
- The more sides you use, the more the shape looks like a circle.
π Words to know
- loop
- a piece of code that repeats
- penup
- lift the pen so the turtle moves without drawing
- polygon
- a shape made of straight sides
π Watch this
A hexagon: six sides, and six turns of 60 that add up to 360.
repeat 6 [ forward 80 right 60 ]
βοΈ Your turn
- Run it and count the sides.
- Change 6 and 60 to 3 and 120. You get a triangle.
- Work out the turn for a nine-sided shape, then draw it.
- Try repeat 36 [ forward 12 right 10 ] and see what appears.
- Write down how many lines you saved by using repeat.
π― Challenge: Draw a pentagon and an octagon side by side on the same page.
Show me one answer
repeat 5 [ forward 80 right 72 ] penup goto -150 0 pendown repeat 8 [ forward 50 right 45 ]
Your program