Python related problem

What are local variables and global variables in Python?

Global Variables:

Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.

Local Variables:

Any variable declared inside a function is knowns a local variable. This variable is present in the local space and not in the global space.

1 Like

Hey @mukulpathak437 ,

You can also understand this concept with the help of an easy example.

Global variables are like free PCO booth in your area. Anyone can access it anytime without any restrictions.
Likewise any function can access this type of variable.

Whereas, Local variables are your mobile phones which can be used by specific users. Others users are restricted to use that.
You decide the functions which will have access to that variable.

Hope this will clear your doubts.


The local variable - using local variable code running only particular reason.
The global variable - using global variable code running overall code.
Example :
You made a python code using calulater you are important maths module add, sub run very time so you use global variable

In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.
A variable declared inside the function’s body or in the local scope is known as local variable.
CAAN help you out to understand
Video link can refer

Thank you.

A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.

In the given code

q = "I love coffee" # global variable
def f():
    p = "Me Tarzan, You Jane." # local variable
    print p
print q

The output is as follows

Me Tarzan, You Jane. I love coffee

In the given code, p is a local variable, local to the function f(). q is a global variable accessible anywhere in the module.

Global variable once declared can use anywhere in the whole code. It can be accessed even inside the functions. Whereas, Local variables are bound to the local function only. They cannot be used outside the local function. Local variables of a function differ from the local variables of another function.