Khan
Khan

Reputation: 33

I don't understand how my list index is out of range

j stops counting when it hits 5 although my range ends at 11.

Why is it happening and how can I solve it?

Part of my code that holds the problem:

dice1 = random.randrange(1,7)

def probabilities_sum():
    print('\nprobability for 2 dices:')
    for j in range(1, 12):
        percentage_2 = (count[j] / freq) * 100
        procent_2 = str(percentage_2)
        print('this is J', j)
        print(j + 1, ':', procent_2)

Upvotes: 1

Views: 66

Answers (1)

Ali Hassan
Ali Hassan

Reputation: 966

Basically what you are mistaken is your are starting your loop from 1, and your count index is starting from 0, so when you are calculating percentage_2 so it was starting from index 1 e.g: percentage_2 = (count[1] / freq)*100, it was skipping your 0th index and when you reached on j=11 so there is an index range of count is 0-10 and there is no value lies on count[11] that's why there was an index out of range error.

import random
count = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dice1 = random.randrange(1,7)
freq = 12
def probabilities_sum():
    print('\nprobability for 2 dices:')
    for j in range(1, 12):
        percentage_2 = (count[j - 1] / freq) * 100
        procent_2 = str(percentage_2)
        print('this is J', j)
        print(j + 1, ':', procent_2)

probabilities_sum()

Output

Upvotes: 1

Related Questions