Home > Back-end >  IndexError: string index out of range , hangman game
IndexError: string index out of range , hangman game

Time:05-29

x = False
tries = 6


def drawgrid():
  global tries
  #  the variable is local so it will give a error by calling it in a function so by making it global it works as long as you add "global variable"
  if tries == 6:
     print("   _____ \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "__|__\n")

  elif tries == 5:
    print("   _____ \n"
            "  |    0 \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "__|__\n")
  
  elif tries == 4:
    print("   _____ \n"
            "  |    0 \n"
            "  |    | \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "__|__\n")
  elif tries == 3:
    print("   _____ \n"
            "  |    0 \n"
            "  |    |- \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "__|__\n")
    
  elif tries == 2:
    print("   _____ \n"
            "  |    0 \n"
            "  |   -|-\n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "__|__\n")

  elif tries == 1:
    print("   _____ \n"
            "  |    0 \n"
            "  |   -|-\n"
            "  |   / \n"
            "  |      \n"
            "  |      \n"
            "  |      \n"
            "__|__\n")

  elif tries == 0:
    print("   _____ \n"
      "  |    0 \n"
      "  |   -|-\n"
      "  |   / \ \n"
      "  |      \n"
      "  |      \n"
      "  |      \n"
      "__|__\n")
      
    


def mainLoop():
  global tries

  print('Hello, please choose a word')
  hangWord = input('')
  operation4 = len(hangWord)
  lettersOfWords =list(hangWord)

  #print(lengthOfWord)
  while x == False:
    print('enter a letter')
    letter = input('')
    if operation4 == 4:
      if letter != lettersOfWords[0] and letter != lettersOfWords[1] and letter != lettersOfWords[2] and letter != lettersOfWords[3]:
        print('Try again ')
        print('?','?','?','?')
        tries -= 1
        drawgrid()
        print(f'{tries} lifes are left')
      elif letter == lettersOfWords[0]:
        print(letter[0],'?','?','?')
        print('First letter found')

      elif letter == lettersOfWords[1]:
        print('?',letter[1],'?','?')
        print('second letter found')

      elif letter == lettersOfWords[2]:
        print('?','?',letter[2],'?')
        print('Third letter found')
        
      elif letter == lettersOfWords[3]:
        print('?','?','?',letter[3])
        print('Fourth letter found')
      
      

  

drawgrid()
mainLoop()

I keep getting this error File "c:\Users\Tameem\Advanced HTML CSS Javascript\Python\test.py", line 105, in mainLoop print('?',letter[1],'?','?') IndexError: string index out of range but the word is 4 character longs so the first letter works but all others dont they give the same error. please explain why i got this error and how to fix. i am new to python, i tried to fix it but i dont know how. thank you

CodePudding user response:

Lets say the word is "Hello". lettersOfWords = ['H','e','l','l','o']. So when you print say letter[3] because you guessed the letter 'l', so you are saying "give me the 4th index of the string 'letter'", but letter is a string with only one character, so you get an index error. lettersOfWords[3] does exist though, since the 4th index of that list is 'l'.

CodePudding user response:

remove index from conditions

def mainLoop():
global tries

print('Hello, please choose a word')
hangWord = input('')
operation4 = len(hangWord)
lettersOfWords = list(hangWord)
while not x:
    print('enter a letter')
    letter = input('')
    if operation4 == 4:
        if letter != lettersOfWords[0] and letter != lettersOfWords[1] and letter != lettersOfWords[2] and letter != \
                lettersOfWords[3]:
            print('Try again ')
            print('?', '?', '?', '?')
            tries -= 1
            drawgrid()
            print(f'{tries} life are left')
        elif letter == lettersOfWords[0]:
            print(letter, '?', '?', '?')
            print('First letter found')

        elif letter == lettersOfWords[1]:

            print('?', letter, '?', '?')
            print('second letter found')

        elif letter == lettersOfWords[2]:
            print('?', '?', letter, '?')
            print('Third letter found')

        elif letter == lettersOfWords[3]:
            print('?', '?', '?', letter)
            print('Fourth letter found')

CodePudding user response:

As others have mentioned, the issue arises from indexing the incorrect variable. Here is a method that doesn't use indexing which I have taken the liberty of extending to cases other than a 4 character input:

def drawgrid(tries):
    if tries == 6:
        print('''   _____
                    |
                    |
                    |
                    |
                    |
                    |
                  __|__''')

    elif tries == 5:
        print('''   _____
                    |    0
                    |
                    |
                    |
                    |
                    |
                  __|__''')
    
    elif tries == 4:
        print('''   _____
                    |    0
                    |    |
                    |
                    |
                    |
                    |
                    __|__''')
    elif tries == 3:
        print('''   _____
                    |    0
                    |    |-
                    |
                    |
                    |
                    |
                  __|__''')
        
    elif tries == 2:
        print('''   _____
                    |    0
                    |   -|-
                    |
                    |
                    |
                    |
                  __|__''')

    elif tries == 1:
        print('''   _____
                    |    0
                    |   -|-
                    |   /
                    |
                    |
                    |
                  __|__''')

    elif tries == 0:
       print(r'''   _____
                    |    0
                    |   -|-
                    |   / \
                    |
                    |
                    |
                  __|__''')
      
    
def add_suffix(i):
    i  = 1
    if i == 1:
        return str(i) 'st'
    elif i == 2:
        return str(i) 'nd'
    elif i == 3:
        return str(i) 'rd'
    else:
        return str(i) 'th'

def mainLoop(tries=6):
    hang_word = input('Hello, please choose a word')
    output = ['_' for _ in hang_word]
    drawgrid(tries)

    while tries:
        letter = input('Please enter a letter')
        
        if letter not in hang_word:
            print('Try again ')
            print(' '.join(i for i in output))
            tries -= 1
            drawgrid(tries)
            print(f'{tries} lives are left')
            if not tries:
                print('You lose')
        elif letter in output:
            print(f"You've already guessed {letter}. Try again.")
        else:
            found = [i for i, char in enumerate(hang_word) if char==letter]
            output = [j if i not in found else letter for i, j in enumerate(output)]
            if len(found) == 1:
                print(f'{add_suffix(*found)} letter found')
            else:
                print(', '.join(add_suffix(i) for i in found[:-1]) f' and {add_suffix(found[-1])} letters found')
            print(' '.join(i for i in output))
            if not any(i == '_' for i in output):
                print('You win')
                break
        
mainLoop()

  • Related