Game Development Reference
In-Depth Information
9 - Hangman
much like the
while
loops we have already seen).
for
Loops
The
for
loop is very good at looping over a list of values. This is different from the
while
loop, which loops as long as a certain condition is true. A
for
statement begins
with the
for
keyword, followed by a variable, followed by the
in
keyword, followed by a
sequence (such as a list or string) or a range object (returned by the
range()
function),
and then a colon. Each time the program execution goes through the loop (that is, on each
iteration
through the loop) the variable in the
for
statement takes on the value of the next
item in the list.
For example, you just learned that the
range()
function will return a list of integers.
We will use this list as the
for
statement's list. In the shell, type
for i in range
(10):
and press Enter. Nothing will happen, but the shell will indent the cursor, because it
is waiting for you to type in the for-block. Type
print(i)
and press Enter. Then, to tell
the interactive shell you are done typing in the for-block, press Enter again to enter a blank
line. The shell will then execute your
for
statement and block:
>>> for i in range(10):
... print(i)
...
0
1
2
3
4
5
6
7
8
9
>>>
Notice that with
for
loops, you do not need to convert the range object returned by the
range()
function into a list with
list()
.
For
loops do this for us automatically.
The
for
loop executes the code inside the for-block once for each item in the list. Each
time it executes the code in the for-block, the variable
i
is assigned the next value of the
next item in the list. If we used the for statement with the list
[0, 1, 2, 3, 4, 5,
6, 7, 8, 9]
instead of
range(10)
, it would have been the same since the
range()
function's return value is the same as that list: