Go Back

What are local variables and global variables in Python?

9/9/2021
All Articles

#local_variables #global_variables #interview #question #pythonVariable #GlobalVariable #LocalVariable

What are local variables and global variables in Python?

What are local variables and global variables in Python?

Local variable: Any variable declared inside a function is known as Local variable and it’s accessibility remains inside that function only.

Global Variable: Any variable declared outside the function is known as Global variable and it can be easily accessible by any function present throughout the program.

 


g=4       #global variable
def func_multiply():
l=5       #local variable
m=g*l
return m
func_multiply()

ouput:


Output: 20

Feature of Local variable :

Scope: Local variables are declared and used within a specific block of code, such as a function or a code block defined by indentation .
Visibility: Local variables are only visible and accessible within the scope in which they are defined.
Lifetime: Local variables have a limited lifetime. They are created when the block of code is entered and destroyed when the block is exited.
Shadowing: If a local variable has the same name as a global variable, it "shadows" or takes precedence over the global variable within the local scope.
 

Feature of Global Variable :

 
Scope: Global variables are declared at the top level of a Python script or in the global scope. It is not defined inside any function or code block.
Visibility: Global variables are visible and accessible from any part of the code, both within and outside functions.
Lifetime: Global variables persist throughout the execution of the program, as long as the program is executing.
Modifiability: Global variables can be modified and accessed from any part of the code.

Conclusion

In this Article , we see global variables should be used with caution because they can reduce the modularity and make the code more complex.

Using local variables within functions to encapsulate logic and lessen the reliance on global state is generally seen as good practise.

This Solution is provided by Shubham mishra This article is contributed by Developer Indian team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.Also folllow our instagram , linkedIn , Facebook , twiter account for more  

Article