In python, the variables access will vary based on the defined scope of variables in the program. In python, you can define three types of variables, i.e., local variables, global variables, and nonlocal variables.
In python, the access scope of local variables is restricted to the function where you defined, and you can't access the local variable outside of the function.
Following is the example of defining the local variables in python.
If you observe the above local variables examples, we defined the greet
variable inside of the greeting()
function and trying to access the greet variable within the greeting()
function.
When you execute the above python example, you will get the result as shown below.
If you try to access the local variable outside of the defined function, you will get an exception. Following is the example of accessing the local variable outside of the function in python.
If you observe the above example, we defined the greet
variable inside of the greeting()
function, but we are trying to access the greet
variable outside of the defined function.
When you execute the above program, you will get an error as shown below.
To access variables anywhere in the program, you need to create variables outside of the function, and those will be called global variables in python.
Following is the example of creating the global variables in python.
If you observe the above example, we defined the global variable msg outside of the function and accessed the same variable inside the function.
In python, if you create a variable inside a function with the same global variable name, that variable scope is limited to that function only. The global variable will remain the same as its original value.
Following is the example of creating the variable inside of function with the same global variable name in python.
If you observe the above example, we created a variable (msg
) inside of the greeting
function with the same global variable name (msg
).
When we execute the above program, we will get the result as shown below.
If you observe the above result, the scope of the variable that we defined inside of the function with the same global variable name is limited to within the function.
In python, you can also share the global variables across multiple modules in the program by creating a separate module to hold global variables. You can import the global variables module in your program wherever it is required based on your requirements. We will learn more about it in the next chapters.