# Hangman game, with the number of guesses depending on the word length

This is an interactive game between the computer and the player, where the computer chooses a word and the user has to guess the letters in that word.

The computer provides certain number of guesses to the user.

Below is my code:

import random
import string

inFile = open("words.txt", 'r', 0)
wordlist = line.split()
print "  ", len(wordlist), "words loaded."
return wordlist

def choose_word(wordlist):
return random.choice(wordlist)

def avail_letters(guesses,guess):
return guesses.replace(guess,'')

def fill_blank(random_word,blank,guess):
blank_new=''
for i,l in enumerate(random_word):
if l==guess:
blank_new+=guess
else:
blank_new+=blank[i]
#print blank_new
return blank_new

def hangman():
random_word=choose_word(wordlist)
##    print random_word
len_word=len(random_word)
print "I am thinking of a word that is ",len_word," letters long."
print "-------------"
no_of_guesses=len_word*2
guesses=string.ascii_lowercase
guess=''
blank="_"*len_word
while no_of_guesses:
print "You have ",no_of_guesses," guesses left."
guesses=avail_letters(guesses,guess)
print "Available letters: ",guesses
if guess in random_word and guesses:
blank=fill_blank(random_word,blank,guess)
print "Good guess: ",blank
else:
print "Oops! That letter is not in my word: ",blank
no_of_guesses-=1
print "-------------"
if blank==random_word:
print "Congratulations, you won!"
break;
else:
print "Sorry, you lose!"


• The idea of splitting the code into smaller functions works, the first methods you have are 10 lines or less and is not hard to follow what they do. Would be interesting to go ahead and split some parts of hangman() into smaller pieces as well
• The name of the variable for your application main loop can be a bit misleading, would suggest something different instead of no_of_guesses, you could think of a can_guess(counter) boolean function that checks a counter and returns if the counter reached zero
• Another part that may be tricky to understand is if blank==random_word, could be easier to read if it was more verbose about what happens, like in if not has_more_characters_to_guess(random_word)
• As a general advice, don't be shy to have longer function names. available_letters is preferred to any shorter name. fill_blank can be replaced with get_partial_word_guess which may be more legible and explain a bit more on the insights