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

Using "while" to Repeat

We need to let the player take more than one turn.

The "while" command can repeat our program until the player is out of turns.

#!/usr/bin/env python

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

while turns > 0:
  for letter in secret:
    if letter in guesses:
      print letter,
    else:
      print '_',

  print
  guess = raw_input('guess a letter: ')
  guesses += guess
  turns -= 1

You need to indent everything under the "while" command to make this work. So you will need to add some spaces in front of most of your program.

Let's also move the guessing after the hint instead of before.

The command "turns -= 1" means subtract one from "turns," so if it used to be 5, it will be 4. Then the next time around it will be 3 and so on. When turns is finally zero, the "while" command will stop repeating.

Try running your program. Does it work?