Data Analysis with Python Projects - Mean-Variance-Standard Deviation Calculator-Problem

Hi everyone!

I have a problem with my code. When the test checks if there is less then 9 values in the input an error return appears in the scream. I was not able to fix this error.


ERROR: test_calculate_with_few_digits (test_module.UnitTests)

Traceback (most recent call last):
File “/home/runner/IdolizedIncompleteFan/”, line 18, in t
self.assertRaisesRegex(ValueError, “List must contain nine numbers.”,
mean_var_std.calculate, [2,6,2,8,4,0,1,])
File “/usr/lib/python3.8/unittest/”, line 1357, in assertRaisesR
return context.handle(‘assertRaisesRegex’, args, kwargs)
File “/usr/lib/python3.8/unittest/”, line 202, in handle
callable_obj(*args, **kwargs)
File “/home/runner/IdolizedIncompleteFan/”, line 56, in
return dictionary
UnboundLocalError: local variable ‘dictionary’ referenced before assignme


import numpy as np

def calculate(list):
if len(np.array(list)) == 9:
array = np.array(list).reshape(3, 3)

  i = 0
  c_mean_vector = []
  c_var_vector = []
  c_std_vector = []
  c_max_vector = []
  c_min_vector = []
  c_sum_vector = []

  for i in range(3):
    c_mean_vector.append(array[:, i].mean())
    c_var_vector.append(array[:, i].var())
    c_std_vector.append(array[:, i].std())
    c_max_vector.append(array[:, i].max())
    c_min_vector.append(array[:, i].min())
    c_sum_vector.append(array[:, i].sum())

  j = 0
  r_mean_vector = []
  r_var_vector = []
  r_std_vector = []
  r_max_vector = []
  r_min_vector = []
  r_sum_vector = []

  for j in range(3):
    r_mean_vector.append(array[j, :].mean())
    r_var_vector.append(array[j, :].var())
    r_std_vector.append(array[j, :].std())
    r_max_vector.append(array[j, :].max())
    r_min_vector.append(array[j, :].min())
    r_sum_vector.append(array[j, :].sum())

  mean_vector = [c_mean_vector, r_mean_vector, array.mean()]
  var_vector = [c_var_vector, r_var_vector, array.var()]
  std_vector = [c_std_vector, r_std_vector, array.std()]
  max_vector = [c_max_vector, r_max_vector, array.max()]
  min_vector = [c_min_vector, r_min_vector, array.min()]
  sum_vector = [c_sum_vector, r_sum_vector, array.sum()]

  dictionary = {'mean': mean_vector,
            'variance': var_vector,
            'standard deviation': std_vector,
            'max': max_vector,
            'min': min_vector,
            'sum': sum_vector

except TypeError:
print(‘List must contain nine numbers.’)
return dictionary

The code is not so good, but it works. The only problem is the condition that checks if the input list has seven elements.