Hardware Reference
In-Depth Information
The loop you will use here is called a
for
loop, sometimes called a
counted loop
because it counts a fixed number of times.
The
for
loop is called a
counted loop
or a count controlled loop, because it
counts a fixed number of times. You decide, in the
range()
statement, how
many times it counts. The
for
loop in Python is quite special because it can
count things other than just numbers, and you will meet its more advanced uses
in Adventure 6.
Just as you did with the
while
loop you used to build your game loop in Adventure 2,
you must indent the program statements that belong to the
for
loop, so the Python
language knows that only these statements should be repeated every time the loop
runs.
To understand how this works, use the Python Shell to try out a
for
loop by following
these steps:
1.
Click the Python Shell window, just to the right of the last >>> prompt.
2.
Type the following and press the Enter key on the keyboard:
for a in range(10):
Python won't do anything yet, because it is expecting the program statements
that belong to the loop (these are often called the loop body).
3.
The Python Shell automatically indents the next line for you by one level, so that
Python knows that your
print()
statement belongs to the
for
loop. Now type
in this
print()
statement:
print(a)
4.
Press the Enter key twice. Your first press marks the end of the
print()
state-
ment; your second tells the Python Shell that you have finished the loop.
You should now see the numbers 0 to 9 printed on the Python Shell screen.
DIGGING INTO THE CODE
The
for
loop that you just used has some interesting features:
for a in range(10):
print(a)