How to fix it? 'int' object is not subscriptable

Here is the task: Generate 20 random integers in the range from -5 to 4, write them to the cells of the array. Calculate how many of them are positive, negative and zero values. Display the array elements and the calculated quantities. Here is the error text:
a[i]=int(a[i]) TypeError: 'int' object is not subscriptable. How can I fix this?thank you very much!

import random
a=[]
for i in range(20):
      a=random.randint(-5,4)
p=[]
n=[]
z=[]
for i in range(20):
     a[i]=int(a[i])
     for i  in range(0,20,1):
            if(a[i]>0):
                p.append(a[i])
            if(a[i]==0):
                z.append(a[i])

            if (a[i]<0):
               n.append(a[i])


print('quantity positive',len(p))
print('quantity negative',len(n))
print('quantity zero',len(z))
Author: Awesome Man, 2017-01-15

1 answers

In the 4th line, you write an integer to the variable "a" :

a=random.randint(-5,4)

Then, in the 9th line, you try to access the variable " a " by index.

a[i]=int(a[i])

But integer variables don't know how to index. To make everything work, you need to replace the 4th line with this:

a.append(random.randint(-5,4))

In general, your code is not too pythonic. Where possible, it is recommended to use list inclusions instead of loops. They are much more concise, and the code with them becomes much easier than without them.

Your program can be rewritten this way:

import random


a = [random.randint(-5,4) for _ in range(20)]

p = [i for i in a if i > 0]
n = [i for i in a if i < 0]
z = [i for i in a if i == 0]

print('quantity positive', len(p))
print('quantity negative', len(n))
print('quantity zero', len(z))

As you can see, it turned out much clearer than you did.

PS: It is considered a sign of good style to put spaces to the left and right of "equals", comparison signs and arithmetic symbols. And also a space after the comma.

 13
Author: Xander, 2017-01-15 16:27:03