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.
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!
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))
There are a few issues in your code:
clue = '_' + clue
should be clue = clue + '_'
, since you want to append the underscore, not prepend it. You did it right for the other case, where you have clue = clue + letter
The if
condition is wrong in two ways:
True
, as this will first compare the string with True
, and only then perform the in
operator.clue
(which is the result you are building), but whether it is in the old guesses. So it should be: if letter in old_letters_guessed:
Not a blocking issue, but the stand-alone expressions clue + letter
and clue + '_'
do nothing useful. These lines of code can be removed.
If you fix those issues, your code will work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.