INTRODUCTION |
Computers are particularly good at repeating the same instructions (including turtle commands) over and over again. In order to draw a square, you do not need to enter the commands forward(100) and left(90) four times in a row. It is rather sufficient to tell the turtle to simply repeat the two statements four times. With the instruction repeat, you tell the turtle that some commands should repeat a designated number of times. In order for the computer to know that these commands belong together (forming a program block), they must be equally indented. Typically, we use four spaces for indentation. |
REPEAT - STRUCTURE |
from gturtle import * makeTurtle() repeat 4: forward(100) left(90)
|
MEMO |
With repeat n: you tell the computer that it should repeat one or more instructions n times before it executes further instructions. Everything that is to be repeated must be placed below repeat, and must also be indented. repeat number:
Instructions, that
should be
repeated
|
REPEATING SOUNDS |
from gturtle import * makeTurtle() setPos(-200, 0) right(45) repeat 5: playTone(392, 400) forward(50) right(90) playTone(523, 400) forward(50) left(90)
|
MEMO |
With setPos(x, y) you can directly put the turtle into a designated position in the window without actually making a trace. The two numbers, x and y, are the coordinates relative to the zero point, which is located at the middle of the window. (The coordinate range depends on the size of the window.) You can also specify the pitch of playTone() using a letter according to the musical scale, for example with c, d, etc., or in the one-line octave with c', d', etc. (or with two or three apostrophes). You have to put quotation marks around the pitch. If you want, you can also indicate a musical instrument to be used (available are: piano, guitar, harp, trumpet, xylophone, organ, violin, panflute, bird, seashore). Try it once with:
|
NESTED REPEATS |
from gturtle import * makeTurtle() # hideTurtle() repeat 20: repeat 4: forward(80) left(90) right(18)
|
MEMO |
The repeat commands can be nested. It is very important to have the correct indentations in the statements which are to be repeated. |
EXERCISES |
1. | Draw a staircase with seven steps. | |||
2. | Draw a star using the back() command. | |||
3. | You can draw a “real” star with rotation angles 140° and 80°. | |||
4. | Draw the following figure using two nested repeat statements. The inner repeat block will draw a square. | |||
5. | Draw a pearl necklace.
|
|||
6. | Draw a bird. |