Local and Global Scope in Python
I would like to start by saying:
The bucket of water in my bathroom is mine but the tap of water flowing on the street is ours.
The quote above quote neatly wraps up the idea behind local and global scope.
If a variable has only local scope, you can use it only within that block of statement that it is defined. A block of statement in python is a group of code that are indented with four line. Most times, this block of statement will refer to codes inside of a loop or inside a function. If a variable has global scope it means that you can access and use it from any where inside the program. This is like water in the street. Let us consider an example.
def print_my_name(): my_name = "Joseph" print(my_name) print_my_name()
This will print "Joseph". But if I try to print the variable my_name outside the function it will bring out an error. The interpreter will say that "my_name" is undefined.
def print_my_name(): my_name = "Joseph" print(my_name) print_my_name() # this will output error print(my_name)
In fact, to be more specific, this is the error the interpreter will generate.
Joseph Traceback (most recent call last): File "<string>", line 8, in <module> NameError: name 'my_name' is not defined
Why does it show this error? It is because the variable my_name is has a local scope. It means that it is the property of only print_my_name() function. No one else can use it any where. Any one that wants to use my_name variable must call print_my_function variable. It is like the bucket of water in my bathroom. Anyone that has to use it has to call me.
On the other hand, consider a function like this.
your_name = "James" def print_your_name(): print(your_name) print_your_name()
In this case, my name is not under the block of code belonging to print_your_name. It is not under any block of code. Hence we can say that it has a global scope. print_your_name() function can access and use it just like I can go out to the street to fetch water from a tap that is running. This time, if I attempt to print your_name variable from anywhere, the compiler will not complain that your_name is not defined. Let's take a look.
your_name = "James" def print_your_name(): print(your_name) print_your_name() print(your_name)
As you can see, it works just fine. You can now use is where you want. So when writing your program, you need to think if I just need this variable only in this scope or in the global scope. This will help you do determine if you need a global scope or a local scope.