HomeTurtlegraficsGPanelRobotics WebTigerPython |
Python - Online |
Deutsch English |
YOU LEARN HERE... |
how to use for loops as an alternative to while loops or repeat loops. |
EXAMPLES |
In many programming languages, for loops are a frequently used alternative to while loops and are used in particular when a loop variable is changed by the same value (in Python, an integer value) with each loop pass. The simplest for loops are so-called counting loops in the form
range(n) returns the numbers 0, 1, 2, ... to n-1, i.e. a total of n numbers (it is actually a list with the numbers [0, 1, ..., n-1]). The start value of i is 0 and i is increased by 1 after each loop pass. The instructions in the loop block are therefore repeated n times. This loop corresponds to a while loop with a start value of 0, the loop condition i < n and the value change i = i +1. Note: If i is not used in the loop body, a repeat loop can be used in TigerJython instead of the for loop, which does not require any variables and is therefore easier to understand for programming beginners. Example 1: Drawing a set of lines with a for loop Program:
The general form of a for loop uses range() with three parameters:
The start value start does not have to be 0 at the beginning and the value change step can be any integer (even negative). If step is positive, the instructions in the loop block are repeated as long as i is less than the stop value. The difference between the for loops with 1, 2 or 3 parameters can be clearly seen in the following examples:
Example 3: Using nested for loops
Program:
if (x + y) % 2 == 0 checks whether the sum of the row and column index is an even number. As you can easily see, a filled square must be drawn in this case. The modulo division a % b returns the remainder of the division when a is divided by b as an integer. a % 2 therefore returns 0 if a is even and returns 1 if a is odd.
Example 4: Drawing a moiré pattern Program:
|
REMEMBER YOU... |
The range() function in the for loop can have 1, 2 or 3 parameters (start, stop, step). If there is only one parameter, range(n) returns the numbers 0, 1, 2, ...to n-1, so the commands in the loop are repeated n times (same as with repeat n:) Instead of a for loop, you can always use a while loop. The reverse is not the case, as only integers are permitted for the value change in the for loop. |
TO SOLVE BY YOURSELF |
1) |
|
a) In a row b) In a diagonal |
2) |
|
|
3) |
|