function - Differences between types in Python and their visibility -


i wondering, differences between next 2 functions (python 3.x)

def first_example ():     counter = 0     def inc_counter ():         counter += 1     in range (10):             inc_counter ()  def second_example ():     counter = [0]     def inc_counter ():         counter[0] += 1     in range (10):             inc_counter () 

first function throw exception referenced before assignment, second function works well. explain me, why python remember arrays, not integers?

you assigning counter name in first nested function, making local variable.

in second example, never assign counter directly, making free variable, compiler rightly connected counter in parent function. never rebind name, altering list counter refers to.

use nonlocal keyword mark counter free variable:

def first_example ():     counter = 0     def inc_counter ():         nonlocal counter         counter += 1     in range (10):         inc_counter() 

Comments