Game Development Reference
In-Depth Information
9 - Hangman
print('Your cat is neither fuzzy nor spotted
nor fat nor puffy.')
If the condition for the if statement is False , then the program will check the
condition for the first elif statement (which is catName == 'Spots' . If that
condition is False , then the program will check the condition of the next elif statement.
If all of the conditions for the if and elif statements are False , then the code in the
else block executes.
But if one of the elif conditions are True , the elif-block code is executed and then
execution jumps down to the first line past the else-block. So only one of the blocks in this
if-elif-else statement will be executed. You can also leave off the else-block if you don't
need one, and just have an if-elif statement.
Making Sure the Player Entered a Valid Guess
91. if len(guess) != 1:
92. print('Please enter a single letter.')
93. elif guess in alreadyGuessed:
94. print('You have already guessed that letter.
Choose again.')
95. elif guess not in 'abcdefghijklmnopqrstuvwxyz':
96. print('Please enter a LETTER.')
97. else:
98. return guess
The guess variable contains the text the player typed in for their guess. We need to
make sure they typed in a single lowercase letter. If they didn't, we should loop back and
ask them again. The if statement's condition checks that the text is one and only letter. If it
is not, then we execute the if-block code, and then execution jumps down past the else-
block. But since there is no more code after this if-elif-else statement, execution loops back
to line 87.
If the condition for the if statement is False , we check the elif statement's condition
on line 93. This condition is True if the letter exists inside the alreadyGuessed
variable (remember, this is a string that has every letter the player has already guessed). If
this condition is True , then we display the error message to the player, and jump down
past the else-block. But then we would be at the end of the while-block, so execution jumps
back up to line 87.
If the condition for the if statement and the elif statement are both False , then we
check the second elif statement's condition on line 95. If the player typed in a number or
a funny character (making guess have a value like '5' or '!' ), then guess would not
exist in the string 'abcdefghijklmnopqrstuvwxyz' . If this is the case, the elif
statement's condition is True .
 
Search WWH ::




Custom Search