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

Picking a Random Secret

The only problem with the game is that it always plays the same secret word. We should use the random library to choose a random word.

Add "import random" to the top of your program and change the line that sets up the secret so that it looks like this:

#!/usr/bin/env python

import random

print 'time to play hangman'
secret = random.choice(['tiger', 'panda', 'mouse'])
guesses = 'aeiou'
...

The square brackets [ ] and commas make a list, and the random.choice picks one thing randomly from the list.

Of course, you can make the list as long as you like. Here is a longer list:

...
print 'time to play hangman'
secret = random.choice([
  'crocodile',
  'elephant',
  'penguin',
  'pelican',
  'leopard',
  'hamster',
])
...

You can write a long list on lots of lines like this, as long as you remember to end any parentheses () and brackets [] that you started. Don't forget to put a comma after each thing in the list.