Sometimes, we want to modify a global name from within a local scope. How do we go about doing this?
global_var = 10 def some_function(): global_var = 20 some_function() print(global_var)
The output would be:
10
In the above example, the value of global_var
remains 10
because global_var = 20
is in a local scope.
Similar to the nonlocal
statement, Python provides the global
statement to allow the modification of global names from a local scope.
global_var = 10 def some_function(): global global_var global_var = 20 some_function() print(global_var)
The output would now be:
20
In addition, the global
statement can be used even if the name has not been defined in the global namespace. Using the global
statement would create the new variable in the global namespace.
def some_function(): global x x = 30 some_function() print(x)
This would output:
30
In summary, the global
keyword is used within a local scope to associate a variable name with a name in the global namespace. This association is only valid within the local scope global
is used.
Instructions
This exercise starts the same as the last with paint_gallons_available
declared inside the local scope of the function, print_available()
. The difference now is that paint_gallons_available
is now being accessed by a for
loop in the global scope. This will result in an error.
Run the code to confirm the NameError
on paint_gallons_available
.
Associate the paint_gallons_available
declaration to the global namespace by adding a line to the top of the print_available()
function.
This will allow paint_gallons_available
to be used within the global scope and no NameError
will occur.