prev next 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Using "if" to Choose

In our hangman game, we should show where any guessed letters are. To decide whether to print a line or a letter, we will need to use "if" and "else".

Try changing your program inside TextEdit like this:

#!/usr/bin/env python

print 'time to play hangman'
secret = 'crocodile'
guesses = 'aeiou'

for letter in secret:
  if letter in guesses:
    print letter,
  else:
    print '_',

Don't forget to line everything up, and remember to save it.

What happens when you run it?

The line "if something in something:" makes a choice. If the letter is in our guesses, it prints the letter. Otherwise it prints a little line ("else:" is how you say "otherwise" in python).

Since the whole thing is under the "for something in something", this choice is repeated for every letter.


laptop:~ student$ Desktop/game.py
_ _ o _ o _ i _ e
laptop:~ student$  

Check your spelling and spacing and punctuation if you get errors. Take your time to get it to work.