Python出现IndexError: list index out of range错误,求排查帮助
Hey there! Let's break down why you're hitting that IndexError: list index out of range error and fix it up.
The Root Cause
Take a look at your first for loop:
for x in range(0,9): print("Enter user: ",x) y = [] y.append(input())
Every single time this loop runs, you're creating a brand new empty list with y = []. That means after each iteration, the previous version of y gets tossed out, and by the end of the loop, y only holds the very last input you typed (so its length is just 1).
Then your second loop tries to access y[0] through y[8]:
for z in range(0,9): print(y[z])
Since y only has 1 element, trying to access indexes 1 and beyond immediately triggers the index out of range error.
The Simple Fix
Move the y = [] line outside the first loop. This way, you're adding all your inputs to the same list instead of creating a new one each time:
y = [] # Initialize the list once before the loop starts for x in range(0,9): print("Enter user: ",x) y.append(input()) for z in range(0,9): print(y[z])
Now, every input gets appended to the same y list. After the first loop finishes, y will have 9 elements, and your second loop can safely access each index from 0 to 8 without any issues.
内容的提问来源于stack exchange,提问作者Nahu

