Global and local variables in python; Through this tutorial, i am going to show you what is global and local variables in python and what are difference between global and local variables in python.
Python Global and Local Variable
- Local Variable
- Global Variable
- Difference between global and local variables in python
Local Variable
Which variables are made inside the function in python; They are called local variables.
Note that; Local variables can be used only inside the function in python.
For example:
def valfun(): x = "great" print("Python is " + x) valfun()
Global Variable
Which variables are made outside the function’ They are called global variables.
Note that; Global variables can be used both inside and outside the function in python.
Declaring global variables in python without using global keyword
For example:
x = "great" def valfun(): print("Python is " + x) valfun()
Declaring global variables in python using global keyword
Generally, when you create a variable in python inside any function, that is local variable. And you can not use this variable outside of the function.
You can create/define a global variable inside the function by using the global keyword.
For example:
def valfun(): global x x = "powerful" valfun() print("Python is " + x)
Difference between global and local variables in python
Global variables are variables declared outside a function. Local variables are variables declared inside a function. While global variables cannot be directly changed in a function, you can use the global keyword to create a function that will change the value of a global variable.