Let's say you create a program as follows:
data_points = [1, 2, 3] def mean(data): mean_value = sum(data) / len(data) return mean_value print(mean(data_points))
In this case, we say that the variable data_points
is defined in the global scope: that is, it is available everywhere in this program (after its definition).
However, when we create a function, we are introducing a scope associated with it. Variables that are assigned within the function scope are only available locally within that function, i.e. they are part of the local scope. That means that local variables are available within the function body, but not in the enclosing scopes.
Going back to the example above, the variable mean_value
is assigned within the function mean
, so it is only available locally (i.e. locally to the function mean
). We can use it within the mean
function, but not in the enclosing scope (in this case, the global scope). For instance, the following would be invalid because mean_value
is not available outside the function mean
:
data_points = [1, 2, 3] def mean(data): mean_value = sum(data) / len(data) return mean_value print(mean_value)
However, variables assigned in an enclosing scope can be accessed by code in enclosed scopes. Let's see another example:
seconds_per_hour = 3600 def convert_hours_to_seconds(hours): result = hours * seconds_per_hour return result convert_hours_to_second(24)
In the snippet above, the variable seconds_per_hour
is defined in the global scope (the enclosing scope of the function convert_hours_to_seconds
). When executing the function code, Python will first try to locate the variable seconds_per_hour
in the local scope. If it does not find it, it will proceed to look in the enclosing scopes until it reaches the global scope. In this case, the variable is found in the global scope. If no variable is found in any of the scopes, an exception will be raised.
If we really want to be able to assign values to variables defined in enclosing scopes, we need to expicitly define those variables as global using the global
keyword, like so:
global x; def fun(): x = 1 print(x)
Global variables should be used sparingly, especially if multiple parts of code are changing their values. This is because it can be hard to determin what parts of the code are changing the global variable and how those changes affect the remaining code.