In python programming, there is a term named as python scope. Python variable scope shows the area that any variable is usable or defined. In other words, a scope of a variable means that the location that we can use this variable.
There are two different python scopes. These are given below:
You can also check Python For Loop and Python While Loop
Table of Contents
Python Local Scope is the area that contains inside of a function. In other words, if we define a variable inside a python function, this variable is used only locally in this function. So, this is local scope.
Below, you can find two variables that has local scope. These are x and y.
You can check also Python Operators
Python Global Scope is the area that contains all the python code. Any variable creatd in the main python code is available in global scope and it can be used globally, within functions or any other places in the python code.
Below, you can see the variable z as a global variable that has global scope. X has local scope, so the program will give error that it can not find x.
We can create a global variable within a function also. To do this, we use “global” keyword before the name of the variable. If we create a variable with global keyword within a function, we can use this variable also out of this function.
Here, the output will give the result of this calculation. Because, both of these variables are global variables.
We can use same variable name both as global and as local at the same time. This is not a problem for python programming. In the function that we define this variable, it will have a local scope, so in function the value of this local variable will be used. In the global part of the code, the global value of this variable will be used.
Below, there is a nice example to understand this better.
The output of this code will give firstly the function result and it will print x value as 500. Then it will print the global value of x. This is 100.
In this lesson, we have talked about, scopes of python, Local scope and Global scope. These terms are very critical during coding. Because, variable definitions are one of the most used activities in python and the availability of these variables are important for a true code.
Leave a Reply