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:
In the above example, the value of
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:
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:
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.
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
paint_gallons_available declaration to the global namespace by adding a line to the top of the
This will allow
paint_gallons_available to be used within the global scope and no
NameError will occur.