My Code:
column_counting = {}
total= 0
def freq_table(dataset, index):
for row in dataset[1:]:
total += 1
column = row[index]
if column in column_counting:
column_counting[column] +=1
else:
column_counting[column] = 1
table_percentages = {}
for key in column_counting:
percentage = (column_counting[key]/total) * 100
table_percentages[key] = percentage
return table_percentage
What I expected to happen:
Table percentages to be returned when running the function for a given column
What actually happened:
UnboundLocalError: local variable 'total' referenced before assignment
The code above resolves itself when initialising ‘total’ after defining the function. However, how come it’s ok to initialise the dictionary before the function (column_counting), but not the variable? Thanks in advance for your help.