I started to learn Python. I use Thonny and the Python version is 3.7.9
This Hangman code choses random word from the list successfully and it shows dashes instead of letters. However, when I guess a letter, dash doesn’t get replaced with that letter. So what is wrong with the following code?
import random
import string
from words import words #words.py file with list of words in it
def get_valid_word(words):
word = random.choice(words)
while "-" in word or " " in word:
word = random.choice(words)
return word
def hangman():
word = get_valid_word(words)
word_letters = set(word)
alphabet = set(string.ascii_uppercase)
used_letters = set() #what the user has guessed
#get user input
while len(word_letters) > 0:
print("you have used these letters: ", " ".join(used_letters))
#current word:
word_list = [letter if letter in used_letters else "-" for letter in word]
print("current word: ", " ".join(word_list))
print("current word: ", word)
user_letter = input("guess a letter: ").upper()
if user_letter in alphabet - used_letters:
used_letters.add(user_letter)
if user_letter in word_letters:
word_letters.remove(user_letter)
elif user_letter in used_letters:
print("you already used that letter")
else:
print("invalid character")
#get_valid_word(words)
hangman()
>Solution :
You are only storing upper letters in used_letters. So you should do:
word_list = [letter if letter.upper() in used_letters else "-" for letter in word]