Very easy hangman game with Python
Tags: python, beginners, tutorial
Published: 2022-07-06 11:17:05

Hello. I've just started to learn Python, and with this little hangman game, I would like to put into practice what I know for a moment. 
In this example, I will use only different types of variables and loops "while" and "for" and also conditionals.
For a moment there are no functions, only basic knowledge about Python.  
So let's go...

Everyone knows how to play hangman but I will recall here the rules and translate them to Python code:

1)  **I need some random words**. 
So I create the hangman.py file I import a random library from python, and I create a variable word type string, for this, I use [random words generator on ligne](https://randomwordgenerator.com/)

```
import random

words = "shave pin committee protest mainstream heaven respect precedent failure smell opposed paper translate place crutch flash frog conference koran put ex frighten plane crude innocent doubt minor looting different testify elite tired officer blame objective swim acid book judicial professional stereotype ankle visual trance rib church ride facade cool recover"
```
For a moment word is a big string but I need each word separately to choose a word to guess. To create a list from word string I use the method split() after I extract a random index and its word:

```
import random

words = "shave pin committee protest mainstream heaven respect precedent failure smell opposed paper translate place crutch flash frog conference koran put ex frighten plane crude innocent doubt minor looting different testify elite tired officer blame objective swim acid book judicial professional stereotype ankle visual trance rib church ride facade cool recover"
list_words = words.split()
#print(list_words)
secret_index = random.randint(0, len(list_words)-1)
print(secret_index)
secret_word = list_words[secret_index]
print(secret_word)
```

![print of variables secret_index and sectert_word](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4n6nitvo1t8e4st20lw.png)

2) **A blank line for each letter in the word and number of lives**
Now I need to replace each letter in our secret_word with ligne, and I need to define the number of lives so how many times the player can go wrong. For this I will use a dictionary:

```
hangman={
    'secret_word': secret_word,
    'guess_word': '_' * len(secret_word),
    'lifes': 9,
}
print(f"{hangman['guess_word']}")
print(f"lifes: {hangman['lifes']}")
```

![hangman word](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p3aiq8dswpft7nzv0k3e.png)

3)**Start guessing letters**
For this, we need to input the letters. 
`letter = input("Give my your letter: ")`

4) **
Fill the letter in the blanks if the players guess correctly**
This mechanism is more difficult. For the moment I have all variables but I need to put a letter in right place in my string.
For that, I need to use a while loop. First I create all conditions:

```
while True:
    letter = input("Give my your letter: ")
    if letter in hangman['secret_word'] and letter not in hangman['guess_word']:
        pass
    #here I replace _ by letter
    elif letter not in hangman['secret_word']:
        hangman['lifes'] -=1
    print(f"{hangman['guess_word']}")
    print(f"lifes: {hangman['lifes']}")
    if '_' not in hangman['guess_word']:
        print('Bravo')
        break
    elif hangman['lifes'] <1:
        print('Game over')
        break
```
Now I create a condition that will replace a ligne by a letter so I use a for loop to enumerate all letters in the secrete word to replace them in guess_word. For that, I need to change guess_word in the list of letters
`guess_word_letters = list(hangman['guess_word'])` 

and for loop to enumerate all letters:

```
for index, current_letter in enumerate(hangman['secret_word']):
            if current_letter == letter:
                guess_word_letters[index] = letter
            hangman['guess_word'] = ''.join(guess_word_letters)
```
now all while loop is like this: 

```
while True:
    letter = input("Give my your letter: ")
    if letter in hangman['secret_word'] and letter not in hangman['guess_word']:
        guess_word_letters = list(hangman['guess_word'])
        for index, current_letter in enumerate(hangman['secret_word']):
            if current_letter == letter:
                guess_word_letters[index] = letter
            hangman['guess_word'] = ''.join(guess_word_letters)
    elif letter not in hangman['secret_word']:
        hangman['lifes']-=1
    print(f"{hangman['guess_word']}")
    print(f"lifes: {hangman['lifes']}")
    if '_' not in hangman['guess_word']:
        print('Bravo')
        break
    elif hangman['lifes'] <1:
        print('Game over')
        break
```
And it works:


![working hangman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0dlu2dmjm9fddmj1ypz2.png)