The code above works, but having only 5 items in the list of words to choose you can have an error if you input a number higher than 5, so I put some other words in the list, but I also deleted the lines with the input function where the user is asked to digit the number of the item related to the word to discover.
So:
I imported the random module.
I deleted the input code.
I used the random.sample function to store the word to discover (line 12).
I substituted words[i] with samplecode[0] as label for the word to discover.
I added a space after the underscore in word.append('_ ') to make the number of the letters more evident ( _ _ _ _ _ instead of _____ ).
import random
print("Welcome to Hangman! Guess the word in less than 6 try.")
words= ['utopian','fairy','tree','monday','blue',
'winner','chosen','magician','european',
'basilar','fonsaken','butter','butterfly',
'flipper','seaside','meaning','gorgeous',
'thunder','keyboard','pilgrim','housewife'
]
sampleword = random.sample(words,1)
if(sampleword[0]):
print("The length of the word is: " , len(sampleword[0]))
guesses=0
letters_guessed = []
word = []
for x in range(len(sampleword[0])):
word.append('_ ')
while guesses < 6:
guess=input("Please enter the letter you guess: ")
if(guess in sampleword[0]):
print("The letter is in the word.")
for index, letter in enumerate(sampleword[0]):
if letter == guess:
word[index] = guess
letters_guessed.append(guess)
else:
print("The letter is not in the word.")
guesses=guesses+1
letters_guessed.append(guess)
print("you have guessed these letters: %s"%(''.join(letters_guessed)))
print("Letters matched so far %s"%''.join(word))
print()
if ''.join(word) == sampleword[0]:
break
if guesses==6:
print("Failure. The word was:" , sampleword[0])
else:
print("YOU'VE WON!! Great Job!")
print("You only made %i wrong guesses"%guesses)