INTRODUCTION |
You often have to count during repetition. For that, you need a variable in the repetition block that changes by a certain value in every iteration of the loop. It is easier to do this using a for structure than it is with a while structure. You must first understand the range() function. In the simplest case, range() has a single parameter (also called stop value) and provides a sequence of natural numbers that starts with 0 and ends with the last number before the stop value. You can try this out with a few examples. If, for example, you execute a program with the single statement print range(10), the numbers [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] are written in the output window. Try it out with a few different parameters. As you can see, in our example, the stop value 10 is not included in the list; it rather indicates how many list elements there are. |
FAMILY OF LINES |
|
MEMO |
The statement for i in range(n) runs through the numbers from 0 to n-1, so in other words, a total of n numbers. The places of consolidation of the lines form a quadratic Bézier curve. |
RANGE() WITH TWO PARAMETERS |
from gpanel import * makeGPanel(-20, 20, 0, 40) for i in range(-20, 21): if i < 0: setColor("red") else: setColor("green") line(i, 0, 0, 40) |
MEMO |
The loop for i in range(start, stop) with integer start and stop values begins at i = start and ends at i = stop - 1, where the loop counter i is increased by 1 each time it runs through the loop. Thereby you need to make start smaller than stop, otherwise the loop will never run. |
RANGE() WITH THREE PARAMETERS |
from gpanel import * makeGPanel(0, 40, 0, 40) setColor("red") y = 1 for i in range(2, 41, 2): move(20, y) fillRectangle(i, 1.5) y = y + 2 |
MEMO |
The loop for i in range(start, stop, step) begins with i = start and ends at a value that is less than stop. i is increased by step each time the program runs through the loop. You can also choose negative numbers for the values start, stop and step. I step is negative, i is reduced by step at every iteration; the last value is greater than stop. |
NESTED FOR LOOPS (Moiré) |
from gpanel import * makeGPanel(0, 10, 0, 10) for i in range(11): for k in range(11): line(i, 0, k, 10) delay(50) for i in range(11): for k in range(11): line(0, i, 10, k) delay(50) |
MEMO |
The program might not be very easy to understand, but it is important. At best, you can assume that the loop variable i of the outer loop has a constant value (initially 0) . The inner loop runs with this value for the values k = 0 up to and including 10. Then i is set to 1 and the inner loops run again with this value i, etc. When using the command delay(millisec), the program waits for the given number of milliseconds so that you can observe how the pattern emerges gradually. |
EXERCISES |
|