In this tutorial we going to look at scoping in python, we’ll start from 0 and finish scoping subjects. This tutorial consists of local scope, global scope, naming variables, and global keywords.
What Is Scoping?
We can also use a variable in a different environment than the one in which it was created. This is called scope. The best part of this is using your data regardless of where your data is created.
If we have a function and there is a variable in it, if we use this variable only in this function, it becomes a local scope. As an example, there is a local scope example below.
def Function(): a = 1 print(a) Function()
You can only use the variable “a” above in Function. For example, if you try to use variable and outside, it will give you an error. Such variables are called local scope variables.
def Function(): a = 1 def Function2(): print(a) Function2() Function()
Of course, you can use this variable in the auxiliary function inside the main function. Thus, you can create as many nested functions as you want and use your variables under different conditions.
Global variables can be used in every block. You need to write these variables to the python main body.
x = "Hello" def Function(): print(x) Function()
As we talked about, global variables can be accessed from any structure and are valid for these nested functions.
x = "Hello" def Function(): print("x") def Function2(): print(x) Function()
Here we used a variable in the first function and used it in the second. we don’t necessarily need to use the variable in the first function.
If you use two variables with the same variable name, you can use your variables both globally and locally, the local variable will be valid in the function except as a global variable.
x = "a" def Function(): x = "b" print(x) print(x) Function()
With the global suffix, you can make a local variable global, so you can use a local variable globally.
def Function(): global x Function() print(x)
CONGRATULATIONS, YOU FINISHED SCOPING IN PYTHON!