Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

count first list elements whith index

import random
n=[0]*7
for i in range(7):
    n[i]=random.randint(0,99)
print(*n,sep=' ')
summa=0
for i in range(7):
    if n.index(7)<4:
        summa=summa+n[i]
print(summa)

Here is my code how i can count together first 4 elements of my list all i get is that the number in n.index is not in the list can somoune help like if it outputs numbers 12 43 43 2
56 98 71 i need to count together numbers 12+43+43+2 and then i need to multiply rest numbers that are left 56, 98 and 71
I have tried puting diffrent numbers in n.index but i get the same error

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you try to access index of 7 it will search for 7 which is a number not an index. Try this instead.

import random
n=[0]*7
for i in range(7):
    n[i]=random.randint(0,99)
    print(*n,sep=' ')
summa=0
prdct=1
for i in range(7):
    if n.index(n[i])<4:
    #calculate the sum of first 4 values
        summa=summa+n[i]
    else:
    #calculate the product of the rest values
        prdct=prdct*n[i]
print(summa)
print(prdct)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading