[Tutor] Re: Please critique my hangman.py program
Alan Gauld
alan.gauld at blueyonder.co.uk
Sun Jul 25 10:33:32 CEST 2004
> >> # Evaluate guess against word
> >> letter_correct = 0
> >> for i in range(word_length):
> >> if guess == word[i]:
> >> correct_so_far[i] = guess
> >> letter_correct=1
> >> letters_guessed = letters_guessed + 1
> >
> >Personally I'd use a while loop here:
> >
> > i,letter_correct = 0,False
> > while i < word_length and not letter_correct:
> > if guess == word[i]:
> > correct_so_far[i] = guess
> > letter_correct=True
> > letters_guessed += 1
> > i += 1
> >
> >Same length but I just think the test expresses the intention of
> >the loop better.
>
> I think that there may be a problem with this. For a word that
> has 2 of the same letter. The original way checks for that,
> while the latter way would make "letter_correct" = to "True"
> by the first pass and the while loop would terminate.
Good catch! Although it actually highlights a bug in the first version
too in that a single letter occurruing twice will show up twice in the
letters_guessed total. But I guess(sic) that thats less of an issue
than not filling in all of the blanks... :-)
It can be fixed by pulling it out of the loop and using an if
statement:
# Evaluate guess against word
letter_correct = False
for i in range(word_length):
if guess == word[i]:
correct_so_far[i] = guess
letter_correct=True
if letter_ correct:
letters_guessed = letters_guessed + 1
And my mistake can also be fixed by simply eliminating the second
clause of the while test, but then its not much advantage over the
for/range combo...
Alan G.
More information about the Tutor
mailing list