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

def load_words():
    print "Loading word list from file..."
    inFile = open("words.txt", 'r', 0)
    line = inFile.readline()
    wordlist = line.split()
    print "  ", len(wordlist), "words loaded."
    return wordlist

wordlist = load_words()

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

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

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

def hangman():
##    print random_word
    print "I am thinking of a word that is ",len_word," letters long."
    print "-------------"
    while no_of_guesses:
        print "You have ",no_of_guesses," guesses left."
        print "Available letters: ",guesses
        guess=raw_input("Please guess a letter: ")
        if guess in random_word and guesses:
            print "Good guess: ",blank
            print "Oops! That letter is not in my word: ",blank
        print "-------------"
        if blank==random_word:
            print "Congratulations, you won!"
        print "Sorry, you lose!"

1 Answer 1


dropping you some small comments about the code you posted

  • 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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.