Skip to main content

Refactoring python hangman game code

Recently I was given a hangman homework test and I wrote something like below (python3)..

import secrets


def guess_the_word():
    tries_left = 9
    output = ["_"] * len(secret_word)

    print(str(' '.join([letter for letter in output])).strip())

    while tries_left >= 0 and not secret_word == str(''.join([letter for letter in output])):
        # print tries left
        print("\nYou have {} tries left".format(tries_left))
        # display the _ which is length of the secret_word and fill in _ as and when the user 
        # types correct word

        guessed_letter = input("Guess a letter from secret word:")

        if guessed_letter in secret_word:
            print("You guessed correct")
            for i, x in enumerate(secret_word):
                if x is guessed_letter:
                    output[i] = guessed_letter
        else:
            tries_left -= 1
            print("You guessed incorrect")

        print(str(' '.join([letter for letter in output])).strip())


print("\nWelcome to Hangman Game!\n")
# open words.txt file to read words
with open("words.txt") as words_file:
    words_list = words_file.read().split()
# choose a random word from words_list
secret_word = secrets.choice(words_list)
guess_the_word()

How do I refactor this to use Classes?

vkk07
  • 31
  • 1