Home > other >  My hangman game keeps printing out extra underscores for every correct guess
My hangman game keeps printing out extra underscores for every correct guess

Time:12-26

`

word = input("Input your word> ").strip().lower()

list = []
counter = 6
def counter1():
  global counter 
  counter -= 1  
  return counter

def checker():  
  for index in range(len(word)):
      for index1 in range(len(list)):
        if list[index1] in word[index]:
          location1 = word.find(list[index1])
          print(word[location1], end='')
        else:
          print("_",end='')


def program():
  ask1 = input("Letter> ")
  print()
  if ask1.lower().strip() in list:
    print()
    print("\033[31m","You already picked this!","\033[0m")
    print()
    checker()
    print()
    print()
    program()
      
  elif ask1.lower().strip() not in list: 
      if ask1 in word:
        list.append(ask1)
        checker()
        print()
        print()
        program()

      else: 
        print("\033[31m","WRONG!!","\033[0m")
        print()
        for index in range(len(word)):
          for index1 in range(len(list)):
            if list[index1] in word[index]:
              location1 = word.find(list[index1])
              print(word[location1], end='')
            else:
              print("_",end='')
        print()
        print()
        if counter == 1:
          print(f"You lost!, The answer was >> {word}")
          exit()
        else:
          print(counter1(),"Attempts left")
          print()
        
        
        program()
        
    

program()

`

For some reason, every time the user inputs the correct guess, it adds extra underscores in between the characters. for example in the terminal it looks like this:

letter> b

b___

Letter> r

b__r____

Letter> u

b___r___u___

Letter> h

b____r____u____h

I tried to make a subroutine for checking where the correct guess is supposed to go in the word. I expected the result to reset and redo the for loops everytime but it looks like it's adding extra underscores. Thank you guys!

CodePudding user response:

Your checker() function is faulty. It should check for every letter in the answer whether it is guessed or not. This is done by the following code:

def checker():  
  for index in range(len(word)):
    if word[index] in list:
      print(word[index],end="")
    else:
      print("_",end='')

It loops for all letters in the word. If the letter is found in the list of guessed letters, it prints the letter. If not, it prints an underscore.

  • Related