0

#Program 1

def test(fun, counts=100):
    def f(*args):
        sum = 0
        while counts:
            sum += fun(*args)
            counts -= 1
        return sum
    return f
        
a = test(pow)
a(2, 2)

#Program 2

def test(fun, counts=100):
    def f(*args):
        sum = 0
        for i in range(counts):
            sum += fun(*args)
        return sum
    return f
    
a = test(pow)
a(2, 2)

Question: Why program 1 has the UnboundLocalError: local variable 'counts' referenced before assignment, but program 2 worked?

TrebledJ
  • 8,713
  • 7
  • 26
  • 48
  • Welcome to Stack Overflow! Check out the [tour], and check out [ask] for tips like starting with your own research. If you just google `python UnboundLocalError closure`, you get helpful results. – wjandrea Sep 11 '22 at 14:54

0 Answers0