python - Defining global inside a function -
is possible define global variable inside function? this:
def posities(): global blauw blauw = {"bl1":[0], "bl2":[0],"bl3":[0],"bl4":[0]} global geel geel = {"ge1":[0], "ge2":[0],"ge3":[0],"ge4":[0]} global groen groen = {"gr1":[0], "gr2":[0],"gr3":[0],"gr4":[0]} global rood rood = {"ro1":[0], "ro2":[0],"ro3":[0],"ro4":[0]} global ingenomenpos ingenomenpos = [] or must first declare variables outside of function? because when define them inside function , try acces them function, doesn't recognise it. want declare global variables without first declaring them outside function.
so try acces globals method:
def bezet(): print (str(ingenomenpos)) which results in error:
nameerror: name 'ingenomenpos' not defined
use global statements in functions, nowhere else (it has no effect elsewhere). yes, it'll work, no don't need create global outside first.
this tested in interpreter:
>>> foo traceback (most recent call last): file "<stdin>", line 1, in <module> nameerror: name 'foo' not defined >>> def bar(): ... global foo ... foo = 'baz' ... >>> bar() >>> foo 'baz' the global statement tells python compiler assigning name should set global, not local variable. without statement, use of variable in function becomes local used bind to.
note have call function; global statement being present in function not enough bind name. python doesn't have 'declarations', names exist through binding actions. see naming , binding.
if still see exception, assignment never executed. either haven't called function, or name = value statement never reached (because function returned before line or exception raised).
Comments
Post a Comment