Game Development Reference
In-Depth Information
9 - Hangman
o
w
o
r
l
d
!
>>>
A
while
Loop Equivalent of a
for
Loop
The
for
loop is very similar to the
while
loop, but when you only need to iterate over
items in a list, using a
for
loop is much less code to type. You can make a
while
loop
that acts the same way as a
for
loop by adding extra code:
>>> sequence = ['cats', 'pasta', 'programming',
'spam']
>>> index = 0
>>> while (index < len(sequence)):
... thing = sequence[index]
... print('I really like ' + thing)
... index = index + 1
...
I really like cats
I really like pasta
I really like programming
I really like spam
>>>
But using the
for
statement automatically does all this extra code for us and makes
programming easier since we have less to type. Our Hangman game will use
for
loops so
you can see how useful they are in real games.
One more thing about
for
loops, is that the
for
statement has the
in
keyword in it. But
when you use the
in
keyword in a
for
statement, Python does not treat it like the in
operator you would use in something like
42 in [0, 42, 67]
. The
in
keyword in
for
statements is just used to separate the variable and the list it gets its values from.
The rest of the
displayBoard()
function displays the missed letters and creates the
string of the secret word with all the unguessed letters as blanks.
print('Missed letters:', end=' ')
for letter in missedLetters: