Error with my python code- new programmer and am trying to create a hangman game

Viewed 41
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


def randWord():
    words = []
    with open('sowpods.txt', 'r') as f:
        line = f.readline().strip()
        words.append(line)
        while line:
            line = f.readline().strip()
            words.append(line)
    random_index = random.randint(0 , len(words))
    rWord = words[random_index]
    lowrWord = rWord.lower()
    return lowrWord

def userIn():
    value = input("Guess a letter?\n")
    if value in alpha:
        return value 
    else:
        print("Not in alphabet! Try again")
        userIn()
    return value

def matchWord():
    randoW = randWord()
    myChoice = userIn()
    beta = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

    def printA():
        i = 0
        for i in alpha: 
            if beta[i] == myChoice:
                beta.pop(i)
        print(*beta, sep = ", ") 

    if myChoice in randoW:
        print("You are correct!")
        printA()
    else:
        print("Your are incorrect!")
        printA()

matchWord()

I get an error like :

Traceback (most recent call last):
  File "hangman.py", line 47, in <module>
    matchWord()
  File "hangman.py", line 45, in matchWord
    printA()
  File "hangman.py", line 36, in printA
    if beta[i] == myChoice:
TypeError: list indices must be integers or slices, not str

Sorry if my question is vague, I am just new and quite confused as to why I am getting this error. Thank you for the help and time!

2 Answers

Using for i in alpha you are basically doing, "for each element in my list" and not "from index 0 to N do", so your printA function should be:

def printA():
    for idx, el in enumerate(alpha): 
        if el == myChoice:
             beta.pop(idx)
    print(*beta, sep = ", ")  

using the enumerate function, you can get both index and element from you list

Or you can use the remove method from lists, that receive the element that you want to remove:

def printA():
    for el in alpha: 
        if el == myChoice:
             beta.remove(el)
    print(*beta, sep = ", ")  

In your function:

def printA():
    i = 0
    for i in alpha: 
        if beta[i] == myChoice:
            beta.pop(i)
    print(*beta, sep = ", ") 

You have the redundant i = 0, because the next line overwrites i at each iteration.

Then in the loop: for i in alpha: this sets i to each element of alpha in turn, so, for example, i becomes 'a' first time round and then you get the error in the next line where beta[i] is now invalid because 'a' is not valid as an index into beta.

I think what you meant to write was this:

def printA():
    if myChoice in beta:
        beta.remove(myChoice)
    print(*beta, sep = ", ")
Related