Search code examples
python-3.3traceback

What is wrong with my list index? index error is stated


numbers = []

def easy_mode():
    with open("aa.txt","r") as f:
        for i in range(9):
            numbers.append(f.readline().strip())
        print(numbers)

 from random import randint

 for i in range(9):
    print(numbers[randint(0,8)])

when ever i process this into python the program prints out this error:

Traceback (most recent call last):
  File "N:\Yr 10 CP\Practice\python\Gaming\THE ACTUAL THING.py", line 12, in <module>
    print(numbers[randint(0,8)])
IndexError: list index out of range

can someone please help me and try and fix my code for me, thanks

Alberto


Solution

  • This tabbing is wierd so im not completely sure what is inside the function, but i think that

    from random import randint
    
    for i in range(9):
        print(numbers[randint(0,8)])
    

    is outside of the function and my guess is that you didn't call the function but just loaded the script and it started executing skipping the function and in the end the numbers variable is empty and therefore any index is out of range.

    EDIT: So the working version of the code should look like (given that the file indeed contains at least 9 lines):

    numbers = []
    
    def easy_mode():
        with open("aa.txt","r") as f:
            for i in range(9):
                numbers.append(f.readline().strip())
            print(numbers)
    
    from random import randint
    
    easy_mode()
    for i in range(9):
        print(numbers[randint(0,8)])