The scope of a variable refers to the region in which it is created.
Variables created within a function belong to the local scope variables.
The local scope variables can only be used within function.
def python_function():
name = "John"
print(name)
python_function()
'John'
The name
variable inside the python_function()
scope is the local scope.
A function within a function is also called a nested function.
A variable created inside a function is also available in the nested function.
def python_function():
name = "John"
def welcome_function():
print(name)
welcome_function()
python_function()
'John'
In the above example, the scope of the variable name
is not available outside of a function but, it is available in the nested function (welcome_function()
).
Global variables are those variables that are created in the main body of the Python module file.
It is possible to access global variables from both local and global scopes.
name = "John"
def python_function():
print(name)
python_function()
print(name)
'John'
'John'
In a Python module file and outside of a python_function()
, the name
variable belongs to the global scope.
A variable with the same name inside and outside of a function is treated as a separate variable in Python.
name = "John"
def python_function():
name = "Smith"
print(name)
python_function()
print(name)
'Smith'
'John'
In the above example, you can see the name variables for local and global scope are different, so it printed the different string texts for the same variable name.
The global keyword makes the variable global.
If you want to convert variable local scope to global scope, then you can use global
keyword.
def python_function():
global name
name = "John"
python_function()
print(name)
'John'
Using the global
keyword, we have converted the scope of the local variable to global. Now the local variable is accessible globally.
The global
keyword can be used to change the value of a global variable within a function.
name = "John"
def python_function():
global name
name = "Smith"
python_function()
print(name)
'Smith'
Here, you can see we used the global
keyword to change the value of a global variable within a function.