A for loop will repeat as many times as it is programmed. This means you can choose how many times your code will repeat! Here is the same square code written as a loop in Python. What do you notice?
for x in range(4):
zumi.forward()
zumi.turn_left()
In this example, x is a variable, or placeholder, to keep track of how many times the loop has run. What number do you think the loop starts at? Run the cell below and count the outputs. We have separated the outputs with a one-second delay to make it easier to count. See how the loop prints the value of x, our variable, as it increases by one each iteration.
In [ ]:
for number in range(4):
print(number)
time.sleep(1)
Did you see that the variable starts at 0 and ends at 3? In Python, loops start at 0 and increment by 1 by default. At the beginning of the program, x = 0. By the end of the program, x=3. The variable stops at 3 because the loop will continue as long as x is less than the value in the parentheses. Adding one more to three means x=4. 4 is not less than 4, so the loop stops. Try changing the value in the parenthesis to control the number of iterations. What number does it stop at?
Practice for loops by making a square with four right turns instead of left turns.