Home > Software engineering >  How can i iterate through n number of integer lists do calulations and then display these values w/o
How can i iterate through n number of integer lists do calulations and then display these values w/o

Time:01-01

I want to iterate through afew int lists and extract the value of at the same index of all the lists i each iteration and do calculations with them using python.

i have tried everything that i know and i continue to get the

TypeError: 'int' object is not subscriptable error dsplayed evertime.
user_list =[0, 1, 2] #the iteration should always corespond witht len(user_list)

list2 = [2, 0, 2]
list3 = [1, 0, 0]
list4 = [1, 0, 0]
list5 = [2, 0, 0]
#i had casted all the lists to integers so i can carry out the calculations but didnt still got         the same error.

#Here it errors with TypeError: 'int' object is not subscriptable
for i in range (0, len(user_list)):
    percentage1 = (list3[i] / list2[i]) *100
    percentage2 = (list4[i] / list2[i]) *100
    percentage1 = (list5[i] / list2[i]) *100
#at each interation i want to print the results of the calculations  
    print(f''' {percentage1}%
           {percentage2}%
           {percentage3}%. ''')

CodePudding user response:

There are a couple of issues with your existing code

  1. NameError: name 'percentage3' is not defined
  2. ZeroDivisionError when you try to divide by list2's zero value.

So you can fix that this way-

user_list =[0, 1, 2]

list2 = [2, 0, 2]
list3 = [1, 0, 0]
list4 = [1, 0, 0]
list5 = [2, 0, 0]

for i in range(len(user_list)):
    if list2[i] == 0:
        continue
    percentage1 = (list3[i] / list2[i]) * 100
    percentage2 = (list4[i] / list2[i]) * 100
    percentage3 = (list5[i] / list2[i]) * 100
    print(f'''{percentage1}% {percentage2}% {percentage3}%.''')
  • Related