EllaP EllaP - 2 months ago 4
Python Question

Flaw in hangman program

I need to write a simple hangman function that takes in one string (the word that's being guessed) and a list of letters (the letters that are guessed).
Here is my code so far:

def WordGuessed(Word, letters):
if letters == []:
return False
else:
for i in letters:
if i not in Word:
return False
else:
if i == letters[-1]:
return True


The code usually works, but I am finding that occasionally prints the wrong answer. For example, if

WordGuessed('durian', ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't', 'u'])


It prints False when it should be printing True. Can anyone see where my code is wrong?

Answer

You are returning False as soon as you find a guessed letter that is not in the word. In your example, the very first letter is not in the word.

It would work if instead you loop through Word and check each letter if it is in the array letters:

def WordGuessed(Word, letters):
    if letters == []:
        return False
    else:
        for i in Word:
            if i not in letters:
                return False
        else:
            if i == Word[-1]:
                return True

# prints True
print(WordGuessed('durian', ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't', 'u']))

# prints False, missing 'u'
print(WordGuessed('durian', ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't']))