2

I want to know why my function is returning a None Type. I can't seem to find any answers on this and I'm fairly new to Python. I want to be able to use the values from this in calculations and in plotting a histogram. My code is as follows:

def mean_calc_d(data_col):
  mean_vals = df[data_col].value_counts().keys().tolist()
  mean_counts = df[data_col].value_counts().tolist()
  mean_dict = dict(zip(mean_vals, mean_counts))
  print(mean_dict)

mean_calc_d("month")

The output I get is a nice dictionary:

{'aug': 184, 'sep': 172, 'mar': 54, 'jul': 32, 'feb': 20, 'jun': 17, 'oct': 15, 'dec': 9, 'apr': 9, 'jan': 2, 'may': 2, 'nov': 1`}

Just as an aside, before that, I call in the csv using this code:

dataframe = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv')
df = dataframe #I do this to make a copy in case I destroy any elements inadvertantly 

The problem I run into is that my function, if I check the type, it says it is a None Type, which means I can't use any of the values to calculate anything else beyond the output I'm getting because it is a None Type. The frequent error I get is:

TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

What am I doing wrong? Why am I getting it returning as a None Type? I am fairly new to this and I couldn't seem to find an adequate answer in other threads.

Thanks in advance for your help!

  • 1
    Printing to the console is not the same thing as *returning a value to the caller*. – Martijn Pieters Feb 07 '19 at 17:46
  • 1
    All functions return `None` by default. You can change this by proactively setting a return value - instead of printing `mean_dict`, change that line to `return mean_dict` and the dict will be returned. – n1c9 Feb 07 '19 at 17:47
  • Oh man, thank you so much guys. I honestly just didn't have any idea that functions defaulted with a None value. This has helped me so much in all of my functions. So return actually creates the value, print just prints the output, but it is a None Type so it stops there. Awesome. – Rob LeCheminant Feb 08 '19 at 18:22

1 Answers1

3

mean_calc_d doesn't return anything. Just put return mean_dict at the bottom of it.

Random Davis
  • 6,662
  • 4
  • 14
  • 24