I wrote a function to calculate the mean of a list, and excluding the zeroes, the mean_val() is the function that should output 5.2200932159502855, but instead it outputs 6.525116519937857 even though its the same formula.
The mean_val2 function has the correct output: 5.2200932159502855 but this function doesn't exclude zeroes.
How do I make the mean_val() output 5.2200932159502855 while also excluding the zeroes from the list while also keeping it in this for loop format?
Here is the code + testing code:
val = [4, 3, 5, 0, 9, 3, 6, 0, 14, 15]
val1 = [4, 3, 5, 9, 3, 6, 14, 15]
def mean_val2(val1):
sum = 0
for i in val1:
print(i)
sum += 1 / i
output = len(val1)/sum
return output
def mean_val(val):
sum = 0
for i in val:
if i != 0:
print(i)
sum += 1 / i
output2 = len(val)/sum
return output2
mean_out2 = mean_val2(val1) # 5.2200932159502855 correct output
mean_out = mean_val(val) # 6.525116519937857
print (mean_out, mean_out2)
outputx = len(valx)/sum. The way you have it, the last time through theforloop theoutputxis not updated.