1

A question is about variable scope. Why next next function2 modifies list l

def function1():
    myvar = 1
    l = []
    def function2():                                                             
        l.append(3)
    function2()
    print l

But it gives error "local variable 'myvar' referenced before assignment", if I add next line myvar = 4,

 def function1():
    myvar = 1
    l = []
    def function2():
        myvar += 4                                                               
        l.append(3)
    function2()
    print l

How to modify myvar that is local to function1 within function2 without making myvar belong to the module scope (module global variable)? References to documentation are appreciated!

Cœur
  • 37,241
  • 25
  • 195
  • 267
ashim
  • 24,380
  • 29
  • 72
  • 96
  • You are never **assigning** to `l` in `function2`. Binding (assignment) determines scope. You are rebinding `myvar` so it is local, unless you tell python with a `nonlocal` or `global` keyword to treat it differently. – Martijn Pieters May 27 '14 at 21:51

0 Answers0