At the highest level of access, we have the global scope. Names defined in the global namespace will automatically be globally scoped and can be accessed anywhere in our program.
# global scope variable gravity = 9.8 def get_force(mass): return mass * gravity print(get_force(60))
However, similar to local scope, values can only be accessed but not modified. For example, if we tried to manipulate the value of
# global scope variable gravity = 9.8 def get_force(mass): gravity += 100 return mass * gravity print(get_force(60))
UnboundLocalError: local variable 'gravity' referenced before assignment
We probably shouldn’t be manipulating gravity anyway! Let’s practice accessing values in the global scope to get a hang of it.
Take a look at the two functions defined. One function named
print_available() prints the number of gallons we have available for a specific color. The other function named
print_all_colors_available() simply prints all available colors!
Ponder what might happen when we run the script and then run it to find out!
Whoops! Looks like we have an error with accessing paint_gallons_available
in ourprint_all_colors_available()` function. This is because the dictionary is locally scoped.
Fix the issue by moving
paint_gallons_available into the global scope.