wiederholung
Deutsch   English   

3. REPEAT

 

 

YOU LEARN HERE...

 

that you can encapsulate one or more program lines into a program block and then run it a certain number of times. This saves you a lot of typing and makes the program clearer.

 

 

EXAMPLE

 

To draw a square, the Turtle must execute the forward(100) and left(90) commands four times. You can program this elegantly with repeat.

Program:    

from gturtle import *

repeat 4:
    forward(100) 
    left(90)
► Copy to clipboard
 

The repetition is introduced with repeat 4: . The colon is very important here. If you forget it, you will receive an error message when the program is executed: Colon ':' missing.

You must indent the commands in the following program block by the same space. You always use 4 spaces to do this, but you can also use the tab key to create them. The repetition structure is also referred to as running through a loop.

 

 

TO SOLVE BY YOURSELF


  1. Experiment with the program from the sample example. Change the number of repetitions and the angle of rotation so that the Turtle draws the following figures.
a)


b)


c)


d)


  2. Draw a staircase with 7 steps  

  3.

Draw the adjacent figure. You will also need the back() and dot() functions and the pen color “blue”.

 

  4.

Draw a pearl necklace consisting of 18 pearls (dots). Between the beads, the turtle must take a few steps forward and turn a small angle (e.g. 20°) to the left.

 

  5.

According to an idea by Joshua Goldstein, pretty pictures are created when the Turtle repeatedly executes forward-right pairs of commands. Draw the graphics with

a) forward(300) , right(151) and 92 repetitions

b) forward(300), right(159.72) and 63 repetitions.
You can hide the turtle and move it down at the beginning with back() so that the graphic fits better in the window.

c) Use an internet search engine with the keywords goldstein turtle to search for the article by J. Goldstein and create some more images inspired by it (also with several forward-right pairs).

 

 

 

ADDITIVES: NESTED LOOPS

 

It gets really exciting and challenging when you nest two repeat structures inside each other. You must then always remember that the “inner”, more indented repeat structure is run through first before the “outer”, less indented structure is repeated.

In your example, the inner loop draws a single square and the turtle is located in the bottom left-hand corner of the square. It is then moved forward in the outer loop and the square is drawn again

Program:    

from gturtle import *

repeat 7:
    repeat 4:
        forward(30) 
        right(90)
    forward(30)
Copy to clipboard
 

 

 

TO SOLVE BY YOURSELF


  6.

First try to figure out on a piece of paper what the following program draws. Then run it to confirm your guess.

from gturtle import *
  
repeat 5:
    repeat 4:
        forward(100)
        right(90)
    left(36)