Home > Software design >  String index out of range in for each loop
String index out of range in for each loop

Time:05-20

My code glitches at the point its learning a letter in the code

while not cracked:
   Word = "" # Word auto generates to learn a word
   for element in range(0, len(WordLearning)):
       print(element)
       if(element in LettersItKnows):
           Word = Word   WordLearning[element]
       else:
           if(Word[element] == WordLearning[element]): # Right Here it is weird
               LettersItKnows.append(element)
           else:
               Word = Word   random.choice(Letters) ```

CodePudding user response:

The problem here is that len() returns the number of elements in a list. but when you're getting an element from a list like this: myList[3] the first element is 0 which means that you need to do this:

while not cracked:
    Word = "" # Word auto generates to learn a word
    for element in range(len(WordLearning) - 1):
        print(element)
        if(element in LettersItKnows):
            Word = Word   WordLearning[element]
        else:
            if(Word[element] == WordLearning[element]): # Right Here it is weird
                LettersItKnows.append(element)
            else:
                Word = Word   random.choice(Letters) ```

You can see that all I did here was replace this: range(0, len(WordLearning)) by this: range(len(WordLearning) - 1) I got rid of the 0, because the range() starts on zero by default

Note that in this script if you reach this line: if(Word[element] == ... you'll get might get an error because there is a chance that the Word variable will still equal this: "" so you might fix that problem by setting Word to something that has more letters than the number of elements in the WordLearning variable. I can't really help you though because I don't understand anything about your script

CodePudding user response:

This code will fail as soon as an character not in LettersItKnows is found, because the length of Word will then be equal to element.

  • Related