I am a beginner programmer and I would like to improve in coding and develop my skills. That is why I am asking this question, what should I focus on improving in this code ?

import random
import re

# this is the file that contains all the words
from words import words

# the word that the user needs to guess
the_guess_word = random.choice(words)

n = 0
t = 0

# puts the random picked word in a list
l_guess = list(the_guess_word)
box = l_guess

# somethings are not yet finished
print("Welcome To The Guessing Game . \n You get 6 Guesses . The Words Are In Dutch But There Is 1 English Word . "

 f"\n \n Your Word Has {len(the_guess_word)} letters ")

class hangman():

    t = len(box)
    right_user_input = []

    # should create the amount of letters in the word
    right_user_input = ["." for i in range(len(the_guess_word))]
    k = len(right_user_input)

    while True:

        # the user guesses the letter
        user_guess = input("guess the word : ")

        # if user guesses it wrong 6 times he or she loses
        if n >= 6 :
            print("you lose!")
            print(f'\n the word was {the_guess_word}')

            # loops over until user gets it right or loses
        if user_guess not in the_guess_word:
                print("\n wrong guess try again ")
                n += 1
        if len(user_guess) > 1 :
            print("chose 1 letter not mulitple words ")

        # when user gets it right the list with the dots gets replaced by the guessed word of the user
        if user_guess in the_guess_word :
            print("you got it right")

            # finds the position of the guessed word in the to be guessed the word
            for m in re.finditer(user_guess, the_guess_word):
                right_user_input[m.end()-1] = user_guess

        # checks to see if user guessed all the words right 
        if '.' not in right_user_input:

            # user now needs to put in the full word to finish the game.
            final = input("what is the final word? : ")
            if final == the_guess_word:
                print('YOU GOT IT ALL RIGHT GOOD JOB !!!')

            # loses if he gets it wrong end ends the game 
                print("you got it wrong , you lose ! ")
  • \$\begingroup\$ is words a python file? Shouldn't it be a text file? \$\endgroup\$ Jun 30, 2020 at 7:16
  • \$\begingroup\$ It's unclear what n and t are, can you explain more plz? \$\endgroup\$ Jun 30, 2020 at 12:33
  • \$\begingroup\$ @VisheshMangla the 't' was not useful . i forgot to take it out and for the python file . i don't know how it would work if i tried to implement the text file . \$\endgroup\$
    – bliboy
    Jun 30, 2020 at 15:51
  • \$\begingroup\$ Please see the edits. Please also add a larger summary of your problem with explanation of what you are doing. Not everyone knows hangman here but we do know python. \$\endgroup\$ Jun 30, 2020 at 16:15

2 Answers 2



You have completely failed at implementing a class.

The PEP-8 -- Style Guide for Python suggests naming conventions that every Python program should (must!) follow. For classes, CapWords should be used, so class hangman(): should be class Hangman: or perhaps class HangMan:.

But more seriously, your entire class implementation is broken.

Python scripts are executed, line-by-line, from top to bottom, unless loops, control structures, or call statements cause a branch to another location. A def statement is "executed" by recording the indented program lines, and storing them under the function's name. This means a function doesn't exist until it is executed. For example, consider this script:

    f()                   # Call a non-existent function
except NameError:
    print("The f() function doesn't exist")

def f():                  # Create the "f" function

f()                       # Call the "f" function, and "Hello" is printed.

def f():                  # Change the "f" function by defining a new one.

f()                       # Call the "f" function, and now "Goodbye" is printed.

Similarly, when a class statement is executed, it creates a new namespace and executes indented statements in that namespace, such that any def statements record code as named methods inside that class namespace. Other statements "executed" in the class's name space are intended to create class global variables. You are not supposed to execute complex code directly inside the class definition; code should be inside methods defined inside def statements inside the class.

You don't have a statements creating class global variables inside class hangman():; you have statements executing code in loops, with conditionals. It isn't until the entire execution of the guessing game is complete that the class namespace being constructed finally saved under the hangman name. In short, the class definition isn't finished and the hangman class finally defined until the the moment program exits, so the class was completely useless.

A proper class definition should look more like:

class Hangman:


    def __init__(self, secret_word):
        self._secret_word = secret_word
        self._guesses = 0
        self._right_user_input = "." * len(secret_word)

    def _check_guess(self, letter):
        ... code to check a user guess

    def play(self):
        print(f"""Welcome To The Guessing Game .
You get 6 Guesses . The Words Are In Dutch But There Is 1 English Word .

Your Word Has {len(self._secret_word)} letters""")

        for _ in range(Hangman.MAX_GUESSES):
            user_guess = input( ... )

            print("You lose!")
            print(f"The word was {self._secret_word}")

if __name__ == '__main__':
    the_guess_word = random.choice(words)
    game = Hangman(the_guess_word)

Of course, much here has been omitted.

Note the use of self in the class methods. Note the use of Hangman(the_guess_word) which creates an instance of the Hangman class, and assigns it to game, and then game.play() calls the play(self) method of the Hangman class with the game object as self.

  • \$\begingroup\$ WOW , I didn't know that . I appreciate you telling me this . I will work on implementing this in the future projects. You have been a BIG HELP thanks !! \$\endgroup\$
    – bliboy
    Jun 30, 2020 at 16:05

Cleaner print with implicit string concatenation

print("Welcome To The Guessing Game ." 
      "\n You get 6 Guesses ."
      "The Words Are In Dutch But There Is 1 English Word."
      "\n \n Your Word Has {len(the_guess_word)} letters ")


right_user_input = ["." for i in range(len(the_guess_word))]

can be

right_user_input = ["."]*len(the_guess_word)

Rename variables

n  to chances_over/counter/chances_provided
t to box_length

Remove unnecessary initialization of variables

right_user_input = []
t = 0

Take out while loop out of the class

Edit: You might like : Dataclasses after reading @AJNeufeld post

For using a txt file to store list of words follow these steps.

Create a text file with list of all words each in a new line. Then use

with open("filename.txt") as fp:
    words = fp.readlines()  # words = ["apple", "grapes", .... ]

Alternatively you can store a Python object in a pickle(.pk) file.See Pickle


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.