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

defining a function for the HANGMAN game using a loop in python

i am a beginner in python and would appreciate your help.

I need to define a function(part of the HANGMAN GAME):

def show_hidden_word(secret_word, old_letters_guessed):

secret_word = a string of the word the player needs to guess.
old_letters_guessed = a list that contains the guessed letters by the player thus far.

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

the function needs to return a string made from letters and ‘ _ ‘. the string shows the letters from the old_letters_guessed list that are in the secret_word string in their right place(index), and the rest of the letters the player has not guessed yet as a ‘ _ ‘.

its supposed to look like this:

>>> secret_word = "mammals"
>>> old_letters_guessed = ['s', 'p', 'j', 'i', 'm', 'k']
>>> print(show_hidden_word(secret_word, old_letters_guessed))
m _ m m _ _ s

this is what ive tried to do and it doesn’t work (has to be done using for/ while loop):

def show_hidden_word(secret_word, old_letters_guessed):
 clue = ""
 for letter in secret_word:
  if letter in clue == True:
   clue + letter
   clue = clue + letter
  else:
   clue + '_'
   clue = '_'+ clue
 return clue

Thank you very much!

>Solution :

This should do the trick:

def show_hidden_word(secret_word, old_letters_guessed):
  return " ".join([c if c in old_letters_guessed else "_" for c in secret_word])

secret_word = "mammals"
old_letters_guessed = ['s', 'p', 'j', 'i', 'm', 'k']
print(show_hidden_word(secret_word, old_letters_guessed))
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