Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hangman with dashes in Python – can't figure out why the code is not working

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading