-3

I want to use the num_samples variable that I have defined in the make_averaged function. When I use the variable in fun_averaged it should search it in the scope of its upper level function.

def make_averaged(fn, num_samples=1000):
    def fun_averaged(*args) :
        totalave = 0
        savenum = num_samples
        while not num_samples == 0:
            totalave = fn(*args) + totalave
            num_samples -= 1
        avetagevalue = totalave/savenum
        return avetagevalue
    return fun_averaged

However I get an Error

    while not samples1 == 0:
UnboundLocalError: local variable 'samples1' referenced before assignment
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
Alex
  • 23
  • 3

1 Answers1

0

Changing:

while not num_samples == 0:
    totalave = fn(*args) + totalave
    num_samples -= 1

into:

for _ in range(num_samples):
    totalave = fn(*args) + totalave

Should help. You can access num_samples from the outer function but you cannot assign to it with +=.

I do not recommend it for this case, but in Python 3 you can use nonlocal to actual do what you intend:

nonlocal num_samples
while not num_samples == 0:
    totalave = fn(*args) + totalave
    num_samples -= 1

It works for the first call of fun_averaged. But the next time you call fun_averaged the value of num_samples will be 0.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • I have to use outer function? I thought "fun_averaged(*args)" will search the value of "num_samples" in "make_averaged" because it live inside of "make_averaged" – Alex Mar 26 '16 at 20:35
  • It can see and use it, but it cannot assigned to it. As soon as you use `+=` it considers `num_samples` a local variable. – Mike Müller Mar 26 '16 at 20:38
  • Actually,it can not be used in outer function too.I can only use nonlocal – Alex Mar 26 '16 at 21:02