Python Forum

Full Version: Help! Error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hİ everyone!

tosumup is a huge list so i'll only paste the begining of it
tosumup = [[5, 5, 5, 3, 3, 3, 5, 0, 0, 0, 0, 1, 0, 3, 5, 3, 0, 0, 5, 5, 0, 3, 5, 0, 0, 5, 0, 0, 0, 0, 1, 0, 5, 0, 1, 5, 5, 5, 5, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 3, 0, 0, 0, 0, 5, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 5, 0, 0, 5, 3, 0, -5, 5, 0, 0, 0, 0, 3, 0, 5, 0], [0, 5, -5, 3, 0, 3, 3, 0, 0, 0, -3, 1, 0, 0, 0, 3, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 5, 0, 0, -5, 3, 0, 0, 0, 0, 1, 0, 5, 0], [], []]
zeros = [51, 67, 0, 0, 81, 0, 73, 66, 83, 47, 66, 60, 0, 0, 0, 82, 61, 74, 48, 71, 0, 84, 84, 62, 82, 71, 0, 64, 72, 86, 34, 37, 73, 0, 87, 53, 83, 63, 43, 63, 77, 0, 24, 44, 78, 83, 70, 0, 78, 41, 0, 81, 64, 82, 62]

tosumup has empty lists and zeros has 0's so, to prevent this error:
Error:
a = sums[i]/(len(tosumup[i])- (zeros[i])) ZeroDivisionError: division by zero
I wrote this line but it didn't worked. Can you help me with that?
if tosumup[i] != [] and zeros[i] != 0:


This is my code snippet;
avareges = []
sums = []
for i in range(len(tosumup)):
    s = sum(tosumup[i])
    sums.append(s)
    if tosumup[i] != [] and zeros[i] != 0:
        a = sums[i]/(len(tosumup[i])- (zeros[i]))
        avareges.append(a)
print(avareges)
print(sums)
You could wrap you code in a try/except block that checks for ZeroDivisionError and then decide what you want to happen when it occurs
see Handling Exceptions
Please, always post entire, unaltered error traceback.
It contains valuable information.
(May-22-2020, 12:27 PM)Larz60+ Wrote: [ -> ]Please, always post entire, unaltered error traceback.
It contains valuable information.

Error:
Traceback (most recent call last): File "C:\Users\USER\Desktop\app\ex2.py", line 118, in <module> a = sums[i]/(len(tosumup[i])- (zeros[i])) ZeroDivisionError: division by zero
What if tosumup[i] = [0, 0, 0] ? Then zeros[i] would be 3 i suppose (you don't mention how it is filled). And then the if statement would execute the next line. Which would raise the error you got.
So it is best to always test exactly what you need to check, namely: (len(tosumup[i]) - (zeros[i])) must not be 0.
if (len(tosumup[i]) - (zeros[i])) != 0:
    a = sums[i]/(len(tosumup[i]) - (zeros[i]))
else
    a = None  # I think you need to match the indexes later, so you should add someting.
avareges.append(a)
count = len(tosumup[i]) - zeros[i]
a = s if count < 1 else s / count