(Jul-16-2022, 12:57 AM)PauloDAS Wrote: Hello,Full Explanation:
Someone can explain why my function is returning None, please? I know that, if I add a "return(word)" in the last line of the "else" block, the output doesn't return "None", but neither the letters guessed so far (it's just output the underscores created by the while). Thanks for the help.
def get_guessed_word(secret_word, letters_guessed): ''' secret_word: string, the word the user is guessing letters_guessed: list (of letters), which letters have been guessed so far returns: string, comprised of letters, underscores (_), and spaces that represents which letters in secret_word have been guessed so far. ''' word = "" i = 0 while i < len(secret_word): word = word + "_ " i += 1 j = 0 for char1 in secret_word: j+=1 for char2 in letters_guessed: if char1 == char2 and j != 1: word = word[0:2*j-2] + char2 + word[2*j-1:2*len(secret_word)] elif char1 == char2 and j == 1: word = char2 + word[1:2*len(secret_word)+1] else: word = word return print(word) print(get_guessed_word('house', ['t', 'o', 'k', 'e']))
Output:_ o _ _ e None
You are using
print()
twice in both line 28
and 30
It is important that when returning a value, always return it as a variable, and not a line of code;
def func(x): return print(x) # Not like this print(func("Hello")) # when you do this, you are doing something similar to the following;
print(print("hello"))
Basically printing twice.
# Better def func_better(x): return x # Return as a value print(func_better("Hello")) # This is the correct method