Joelinton
Joelinton

Reputation: 71

Hangman Project trouble in while loop

Can someone help me for this hangman project i want when user will enter one character letter then automatically to check that letter if it is in get_word and from that if it is add to result in the right place not for example if user enters a and the word is banana , if is first written letter a to be not in index 0 but to be in right index , index 1 , index 3 and index 5.Check my code you will understand it better thank you!

import random 

word_list = ['book','banana','peach','car','house','people','chair','table','juice','sleep','window']
get_word = random.randint(0,len(word_list)-1)
get_word = word_list[get_word]
x = "_"*len(get_word)
print("The word is" , x)
attempts = 0
result = ''
while attempts < 5:
    print("Enter a letter")
    guess = input()
    if len(guess) == 1:
        for word in guess:
            if word in get_word:
                result += word
            else:
                result += "_"
    print(result)

Upvotes: -1

Views: 177

Answers (2)

Dylan Dang
Dylan Dang

Reputation: 166

Here's how I would do it

import random

word_list = ['book','banana','peach','car','house','people','chair','table','juice','sleep','window']
get_word = random.choice(word_list)
result = '_' * len(get_word)
guessed = ''

attempts_left = 5
while attempts_left > 0 and '_' in result:
  result = ''.join(c if c in guessed else '_' for c in get_word)
  print('The word is', result)
  print(attempts_left, 'attempts left')
  guess_letter = input("Enter a letter: ")
  if len(guess_letter) == 1 and not guess_letter in guessed:
    guessed += guess_letter
    attempts_left -= not guess_letter in get_word

Upvotes: 1

Nik
Nik

Reputation: 1221

I would iterate over the letters of your word and check if they match with the guess. If yes, replace the "_" with the guess.

import random

word_list = [
    "book",
    "banana",
    "peach",
    "car",
    "house",
    "people",
    "chair",
    "table",
    "juice",
    "sleep",
    "window",
]
get_word = random.choice(word_list)
attempts = 0
result = ["_"] * len(get_word)
print("The word is", "".join(result))
while attempts < 5:
    print("Enter a letter")
    guess = input()
    if len(guess) == 1:
        for i, letter in enumerate(get_word):
            if letter == guess:
                result[i] = guess
        if guess not in get_word:
            attempts += 1
    print("".join(result))
    

Upvotes: 1

Related Questions