Loops
From GeoMod
Loops are statements that command other statements to be executed repeatedly.
While
While loops will go until the conditon in them is satisfied. If the conditon is never satisfied then they will go on forever. For example, the code;
i=0
while i < 5:
i = i + 1
print i
will print out the value of i until it's value is not less than 5. ie.:
1 2 3 4 5
If your condition is poorly posed so that it is never met then the while loop will continue indefinitely.
For
The for loop goes through a specific list of items one at a time. For example;
for i in range(1, 5):
print i
will print out,
1 2 3 4 5
The "range(1,5)" function creates a list of numbers from 1 to 5 (1, 2, 3, 4, 5), and the for loop goes through the list and each time it does so the variable i takes its value from the list.
For loops can also go through lists of items. The following code creates 5 balls in a list using the basic for loop seen above (see the note about the range function). The second for loop goes through the list of balls and changes their color to red.
from visual import *
balls=[]
#Loop 1: Create balls
for i in range(5):
balls.append(sphere(pos=(i*2,0,0)))
#Loop 2: Change ball color
for i in balls:
i.color = color.red
Note that in the second loop, i behaves just like a ball, and you can change its color with i.color, while in the first loop i takes the value of the number from the range function so it can be multiplied in i*2.


