Deutsch English |
YOU LEARN HERE... |
how to use repeating structures with the keywords while and for. The while loop is one of the most important program structures of all. It can generally be used for any type of repetition and is found in practically all programming languages. With repeat, you could previously program simple repetitions without using variables. Now that you know the concept of variables, you can also use the while and for structure. |
EXAMLES FOR WHILE-LOOP |
A while loop is introduced with the keyword while followed by a condition and a colon. As long as the condition is fulfilled, the commands are repeated in the subsequent program block. The comparison operators >, >=, <, <=, ==, != are usually used in the condition. The instructions in the while block must be indented. The repetition structure can be formulated colloquially as follows: “As long as the following condition is met, execute the following program block...”
Programm: from gturtle import * a = 5 while a < 200: forward(a) right(90) a = a + 2 |
Program: from gturtle import * while True: forward(3) right(3) |
REMEMBER... |
The condition a < 200 is also called a run condition. While True initiates an endless loop in which the commands in the loop block are repeated until Stop is pressed. |
TO SOLVE BY YOURSELF |
1. |
|
||||
2. |
|
EXAMPLES FOR FOR-LOOP |
With the for-loop, the loop counter is changed automatically.
Program: from gturtle import * hideTurtle() for s in range(100): forward(s) right(70) You can also draw the next figure with two repeat loops. Since you also need i in the inner loop to calculate the line length, the for loop is more advantageous. Pay attention to the correct indentation!
The general form of a for loop has 3 parameters
|
REMEMBER... |
With for i in range(n):the numbers 0, 1, 2,...(n-1) are run through. The parameter n in range(n) specifies the number of repetitions. A for loop can also have 2 or 3 parameters. |
TO SOLVE BY YOURSELF |
3. |
|
4. | The turtle moves forwards drawing a filled circle (dot), then backwards to the starting point and turns 10° to the right. With each repetition it draws a longer distance. Solve the task with a for loop and use a multiple of the loop counter i for the distance. |
5. | Create the adjacent figure with a for loop. The turtle starts with the path length s forwards and then turns 89° to the right. It should run from 0 to 150. |
ADDITIVEL: NESTED FOR LOOPS |
Program: from gturtle import * for x in range(-200, 201, 20): for y in range(-200, 201, 20): if x + y < 0: setPenColor("red") else: setPenColor("green") setPos(x, y) dot(10)
Program: from gturtle import * def cell(x, y): setPos(x, y) startPath() repeat 4: forward(30) left(90) fillPath() setFillColor("blue") hideTurtle() for i in range(8): for k in range(8): if (i + k) % 2 == 0: cell(30 * i, 30 * k) |