Project: Hangman
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Project: Hangman
- The last project puts the whole course together: a game of hangman.
- You guess a word one letter at a time. Five wrong guesses and you lose.
- You use strings, lists,
in, functions, awhileloop andinput().
English
What you will build
a
_a_
z
_a_
t
_at
c
cat
You won!
English
Plan first
- Before you write the loop, write two small functions and test them:
mask(word, guessed)shows the word with_for letters not guessed yet.is_won(word, guessed)says whether every letter has been guessed.- Then the game loop only has to call them.

English
Step 1: build a string letter by letter
- Start with an empty string
"". - Loop over the word; add the letter, or
_, to the end each time. letter in guessedisTruewhen the list contains that letter.
English
Step 2: stop as soon as you know
- Loop over the letters. If one is not in
guessed,return Falsestraight away. - If the loop finishes, nothing was missing:
return True.
English
Step 3: the game loop
- Keep going while there are fewer than 5 wrong guesses and the word is not won.
- Inside: read a letter, remember it, count it if it is wrong, print the mask.
- After the loop, one
ifdecides between the winning and the losing message.
English
Play for real
- The computer picks a secret word from a list. Type one letter at a time.
English
import random
def mask(word, guessed):
result = ""
for letter in word:
result = result + (letter if letter in guessed else "_")
return result
word = random.choice(["python", "loop", "list", "print"])
guessed = []
wrong = 0
while wrong < 5 and mask(word, guessed) != word:
letter = input("Guess a letter: ")
guessed.append(letter)
if letter not in word:
wrong = wrong + 1
print(mask(word, guessed), " wrong:", wrong)
print("You won!" if mask(word, guessed) == word else "You lost! The word was " + word)
English
Now build it
- Three steps. Well done for reaching the end of the course!
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Step 1: write mask(word, guessed) that 返回值 the word with every letter that is not in the list guessed replaced by _. mask("python", ["p", "o"]) is(是) "p___o_".
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Step 2: write is_won(word, guessed) that 返回值 True when every letter of the word is in guessed, otherwise False.
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Step 3: the game. The word is cat. Read one letter per line with input() and add it to guessed. After each guess print the mask. Count the wrong guesses. Stop when the word is guessed (print You won!) or after 5 wrong guesses (print You lost! The word was cat). For the guesses a, z, t, c, the output is _a_, _a_, _at, cat, You won!.
点击“运行”查看此处输出。