Search code examples
pythonindex-error

How to fix an IndexError Problem for printing words from a list


For my beginning python class we have to write a code that determines if a number is prime, finds the average word length in a sentence, determines which words in a sentence have prime lengths, and then prints the words that have prime lengths. (we don't need to worry about punctuation for this assignment) So I've written the following code, but when I try to print the words that have prime lengths it's returning list index out of range The code works fine through the first for loop, and returns True for however many prime lengths are entered, but I can't get it to print the actual words. Please help!

from statistics import mean


def is_prime(n):
    if n < 2:
        return(False)
    else:
        for i in range(2, n + 1):
            if n == 2:
                return(True)
                break
            elif n % i == 0:
                return(False)
                break
            else:
                return(True) 
                break   
    return


user_input = " "
while user_input != "quit":
    user_input = input("Please enter a random sentence (or type 'quit' to exit): ")
    word_list = user_input.split()
    x = len(word_list)
    word_length = []

    for i in range(x):
        word_length.append(len(word_list[i]))


    for i in word_length:
        if is_prime(i) == True:  
            print(word_list[i])             #I think this is where the problem is???
          
            

    avg = mean(word_length)
    print("Average word length: " + str(avg))
    print("The following words have prime lengths: ")
    
    

while user_input == "quit":
    print("Goodbye!")
    break

Solution

  • Change the second for loop to -

    for i in range(len(word_length)):
        if is_prime(word_length[i]) == True:  
            print(word_list[i])             #I think this is where the problem is???
    

    You are using the actual word length to access an indexed list which doesn't work if the number of elements in the word_list isn't as long as the length of a word. Looping over range(len(word_length)) solves the problem