I wonder why my code is not working. I expected that it would return 11 and instead it creates an exception:
def f():
counter = 1
def f1():
global counter
counter += 1
while True:
f1()
if counter>10:
return(counter)
f()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-219-0ec059b9bfe1> in <module>()
----> 1 f()
<ipython-input-218-50c23b042204> in f()
9 counter += 1
10
---> 11 f1()
12
13 if counter>10:
<ipython-input-218-50c23b042204> in f1()
7 global counter
8
----> 9 counter += 1
10
11 f1()
NameError: name 'counter' is not defined
Since counter is declared a global variable and since it appears and defined in the surrounding environment of f1() --inside f()-- why I receive this error message?
global
. You can usenonlocal
https://mcmap.net/q/813818/-using-a-global-variable-inside-a-function-nested-in-a-function-in-python – Colorblind