I don't understand why I can use series variable here:
def calculate_mean():
series = []
def mean(new_value):
series.append(new_value)
total = sum(series)
return total/len(series)
return mean
But I can't use count and total variables here (variable referenced before assignment):
def calculate_mean():
count = 0
total = 0
def mean(value):
count += 1
total += value
return total/count
return mean
It works only if I use nonlocal keyword like this:
def calculate_mean():
count = 0
total = 0
def mean(value):
nonlocal count, total
count += 1
total += value
return total/count
return mean
This is how I use calculate_mean()
mean = calculate_mean()
print(mean(5))
print(mean(6))
print(mean(7))
print(mean(8))