Skip to content
Advertisement

Python hangman Game explaination

I’m having problems wrapping my head around this for loop code. which was part of a Udemy course online and the teacher’s code for the hangman project.

This part I understand as we are casting the number of letters in the chosen word into an underscore.

display = []
for _ in range(length_of_word):
    display += "_"

This is the part I just do not understand. line 2 – inside the for loop, position is a variable we use to find a length? line 3 – letter is a variable, but why the [] brackets? line 4 – again the [] brackets and their meaning.

word_list = [item1, item2, item3]
chosen_word = random.choice(word_list)
guess = input("Enter in a letter. ")
length_of_word = len(chosen)word

for position in range(length_of_word):
    letter = chosen_word[position]
    if letter == guess:
        display[position] = letter
print(display)

Advertisement

Answer

Note: Your chosen_word variable has the value that it took randomly from “word_list”.

Here, chosen_word[position] is accessing a letter of that word in the positionth index number. for example position is 2. Then, its chosen_word[2]. if you take “stack” as a word here chosen_word[2] is “a”. This letter assigned in your “letter” variable. Then checking with your given letter input. for the condition true, its assigning the value in “display” list with that checked index position and that letter.

Example-

chosen_word = "stack";
guess = "s";
position = 0 ;
letter = chosen_word[position]; //now at oth index value which is "s"

if condition is true now assigning at the same index position of that letter found in the list variable display

display[position] = letter; //display[0] = "s"

I hope this answer could help you.

Advertisement