Scope defines the visibility of a variables to other part of the code.
x = 25 def printer(): x = 50 return x print x print printer()
Python has a set of rules it follows to decide what variables (such as x in this case) you are refrencing in your code. Lets break down the rules:
This idea of scope in your code is very important to understand in order to properly assign and call variable names.
In simple terms, the idea of scope can be described by 3 general rules:
- Name assignments will create or change local names by default.
- Name references search (at most) four scopes, these are:
- enclosing functions
- Names declared in global and nonlocal statements map assigned names to enclosing module and function scopes.
The statement in #2 above can be defined by the LEGB rule.
L: Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function.
E: Enclosing function locals — Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer.
G: Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.
B: Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,etc
# This is a global variable a = 0 if a == 0: # This is still a global variable b = 1 def my_function(c): # this is a local variable d = 3 print(c) print(d) # Now we call the function, passing the value 7 as the first and only parameter my_function(7) # a and b still exist print(a) print(b) # c and d don't exist anymore -- these statements will give us name errors! print(c) print(d)