Python list index out of range error

Asked 2 years ago, Updated 2 years ago, 18 views

import random                            
random.random()

figure=[]
for i in range(1,11):
    fig=random.randint(1,2)
    figure.append(fig)
print(figure)

a=0
for i in range(10):
    print(figure[a])
    a=a+1

for i in range(9):
    if figure[a]==1:
        print ("Kim")
    else:
        print ("Chi")
    a=a+1

In the last for statement, I want to make the output statement different according to each index value of the list, but it is not output due to the list index out of range error continuously.If figure[a]==1 There seems to be a problem here, so I would appreciate it if you could tell me what the problem is.

python

2022-09-20 15:56

1 Answers

With the length of figure 10, the local variable a has already become 10 in the second for statement, but the problem is occurring because we kept using this value in the third for statement.

Try resetting a to zero again


2022-09-20 15:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.