6.9 Variable scope
When I assign a variable, what other code can access and use it? What else can change it? The answers to these questions define the variable’s scope.
6.9.1 Global versus local scopes
Global scope is outside every function definition. Let’s look at how the value of
my_variable
changes inside and outside functions.
my_variable = "SET AT GLOBAL SCOPE"
print(f"Global: {my_variable}")
Global: SET AT GLOBAL SCOPE
def f():
print(f"Inside f: {my_variable}")
f()
Inside f: SET AT GLOBAL SCOPE
print(f"Global: {my_variable}")
Global: SET AT GLOBAL SCOPE
I use my_variable
but do not assign to it. Once I assign to
my_variable
, it changes from global to a local scope.
my_variable = "SET AT GLOBAL SCOPE"
print(f"Global: {my_variable}")
Global: SET AT GLOBAL SCOPE
def g():
my_variable...