In this Python post, you will learn difference between global and local variables in Python.
As the name suggests, the global variable can be declared both inside and outside the function in Python. The local variable can be defined inside the only function.
Basically a variable in python is nothing, but it only holds the data or any values in it. There is no special command to make it. You can easily change it value on runtime.
Understand the global and local variables in Python with the example. How the local and global variables are defined and how they are used in the Python program.
Which variables are made inside the function in python. They are called local variables. Local variables can be used only inside the function in python.
For example:
def valfun():
x = "great"
print("Python is " + x)
valfun()
Which variables are made outside the function. They are called global variables. Global variables can be used both inside and outside the function in python.
For example:
x = "great"
def valfun():
print("Python is " + x)
valfun()
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)
#python