Reputation:
My loop seems to iterate over the first letter and then breaks though it's supposed to iterate through each letter in the secretWord, for example, the code bellow is supposed to print out "_pp_e" but instead it only prints "_". I don't understand, what's the problem with that code??
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
# FILL IN YOUR CODE HERE...
for letter in secretWord:
if letter in lettersGuessed:
return letter
else:
return '_'
print(getGuessedWord("apple", ['e', 'i', 'k', 'p', 'r', 's']))
Upvotes: 0
Views: 1988
Reputation: 519
The return keyword exits the calling function. This should do the trick:
def getGuessedWord(secretWord, lettersGuessed):
result = ''
for letter in secretWord:
if letter in lettersGuessed:
result += letter
else:
result += '_'
return result
print(getGuessedWord("apple", ['e', 'i', 'k', 'p', 'r', 's']))
Here, you start with an empty string as the result and either append a letter (if it was included in the list) or an underscore (if it was not), then return the result string.
Upvotes: 0
Reputation: 1124978
You return
from the function in the first iteration. return
ends a function, there and then, so the for
loop won't continue either.
You need to build up your return value in the function itself. Build up the resulting string one character at a time, by using a list to hold all the characters first then joining those together into one string at the end:
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
guessed = []
for letter in secretWord:
if letter in lettersGuessed:
guessed.append(letter)
else:
guessed.append('_')
return ''.join(guessed)
If you are feeling adventurous, you could even make that a list comprehension and do all the work in one line:
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
return ''.join([l if l in lettersGuessed else '_' for l in secretWord])
Either version produces the expected output:
>>> print(getGuessedWord("apple", ['e', 'i', 'k', 'p', 'r', 's']))
_pp_e
Upvotes: 2