with the addition of nested function scopesvariable lookup rules become slightly more complex within functiona reference (xlooks for the name first in the current local scope (function)then in the local scopes of any lexically enclosing functions in your source codefrom inner to outerthen in the current global scope (the module file)and finally in the built-in scope (the module builtinsglobal declarations make the search begin in the global (module filescope instead an assignment ( valuecreates or changes the name in the current local scopeby default if is declared global within the functionthe assignment creates or changes the name in the enclosing module' scope instead ifon the other handx is declared nonlocal within the function in (only)the assignment changes the name in the closest enclosing function' local scope notice that the global declaration still maps variables to the enclosing module when nested functions are presentvariables in enclosing functions may be referencedbut they require nonlocal declarations to be changed nested scope examples to clarify the prior section' pointslet' illustrate with some real code here is what an enclosing function scope looks like (type this into script file or at the interactive prompt to run it live) def () def ()print(xf ( (global scope namenot used enclosing def local reference made in nested def prints enclosing def local first offthis is legal python codethe def is simply an executable statementwhich can appear anywhere any other statement can--including nested in another def herethe nested def runs while call to the function is runningit generates function and assigns it to the name local variable within ' local scope in sensef is temporary function that lives only during the execution of (and is visible only to code inthe enclosing but notice what happens inside when it prints the variable xit refers to the that lives in the enclosing function' local scope because functions can access names in all physically enclosing def statementsthe in is automatically mapped to the in by the legb lookup rule scopes