python 3.x - Referring to variables of a function outside the function -
#!/usr/bin/python3 def func(): = 1 print(a+12) print(a)
the result is:
nameerror: name 'a' not defined
is possible use a outside function?
in python scope function, or class body, or module; whenever have assignment statement foo = bar
, creates new variable (name) in scope assignment statement located (by default).
a variable set in outer scope readable within inner scope:
a = 5 def do_print(): print(a) do_print()
a variable set in inner scope cannot seen in outer scope. notice code not ever set variable line not ever run.
def func(): = 1 # line not ever run, unless function called print(a + 12) print(a)
to make wanted, variable set within function, can try this:
a = 0 print(a) def func(): global # when use a, mean variable # defined 4 lines above = 1 print(a + 12) func() # call function print(a)
Comments
Post a Comment