def print_guessed(word, user_inputs):
"""
word: a string holding the secret word
use_inputs: a list of letters, collecting the user inputs
returns: None
this function prints the word letter by letter showing
unguessed letters as "*"
So the function might show "P Y * * O N" if the word is "PYTHON" and
the user_input is ["O", "N", "P", "X", "E", "Y"]
"""
result = []
for c in word:
if c in user_inputs:
result.append(c)
else:
result.append("*")
print(" ".join(result))
# some tests
print_guessed("ABCA", [])
print_guessed("ABCA", ["A"])
print_guessed("ABCA", ["A", "C"])
print_guessed("ABCA", ["A", "B", "C"])
def count_guessed(word, user_inputs):
"""
word: a string holding the secret word
use_inputs: a list of letters, collecting the user inputs
returns: the number of letters in "word" appearing in "user_inputs".
"""
count = 0
for c in word:
if c in user_inputs:
count += 1
return count
# some tests:
assert count_guessed("ABCA", []) == 0
assert count_guessed("ABCA", ["A"]) == 2
assert count_guessed("ABCA", ["X"]) == 0
assert count_guessed("ABCA", ["A", "B"]) == 3
assert count_guessed("ABCA", ["A", "B", "C"]) == 4
def ask_new_guess(user_inputs):
"""
user_inputs: list of letters already input by user
returns: new guess from user in upper case
asks until the user provids a new guess, if he repeats a
previous guess a message is displayed and the user is
asked again. Same happens if user inputs empty string
or more than one character
"""
while True:
guess = input("please guess a character: ").upper()
if guess == ".":
return guess
if len(guess) != 1:
print("invalid input")
elif guess in user_inputs:
print("you already tried this character")
else:
return guess
def play_game(secret_word):
user_inputs = []
guesses_left = 5
while True:
print_guessed(secret_word, user_inputs)
guess = ask_new_guess(user_inputs)
if guess == ".":
break
user_inputs.append(guess)
if guess not in secret_word:
guesses_left -= 1
print("WRONG ! %d guesses left !!!" % guesses_left)
if guesses_left == 0:
print("GAME OVER ! THE WORD IS", secret_word)
break
print()
letters_guessed = count_guessed(secret_word, user_inputs)
if letters_guessed == len(secret_word):
print("YOU GOT IT !")
break
import random
secret_words = ["notebook", "pythoncourse"]
secret_word = secret_words[random.randint(0, len(secret_words) - 1)].upper()
play_game(secret_word)