Skip to content Skip to sidebar Skip to footer

Difference Between Local Variable And Global Variable

I'm confused on the difference between local variables and global variables. I know that global variables are declared outside a function while local is declared in a function. How

Solution 1:

l is a location variable that you passed into the function, and so is w since w is a "copy" of l[0]

To have a global variable you need to declare the variable as global using the global keyword.

x = 1
y = 2
def func(l):
    global x 
    x = 4 
    l = 5
    print("x is {0}, y is {1}".format(x,l))

func(y)
print("x is {0}, y is {1}".format(x,y))

Returns:

x is 4, y is 5
x is 4, y is 2

Notice how x is now changed but y isn't?

Note that lists are special because you don't need to declare the global keyword to append or remove from them:

x = []

def func():
    x.append(3)
    print("x is {0}".format(x))

func()
print("x is {0}".format(x))

Returns:

x is [3]
x is [3]

But references to lists are not global because they are a 'copy' of it :

x = [3]
y = 1

def func():
    y = x[0]
    print("y is {0}".format(y))

func()
print("y is {0}".format(y))

Returns:

y is 3
y is 1

Also Reassigning the variable that was a list is not global:

x = [3]

def func():
    x = [2]
    print("x is {0}".format(x))

func()
print("x is {0}".format(x))

Returns:

x is [2]
x is [3]

Also note that there are always a better way to do something than to declare global variables, because as your code scales it will get messier.


Solution 2:

All those variables are assigned values and that automatically declares them in the local scope. So they are local variables.

Even if they had been declared outside in the global scope, they would still be local.

Unless you used the global keyword which tells the interpreter that the current scope refers to a previously declared global or creates a new one in the global context if none with the same name exists.

def func(l):
  global n # n is declared in the global scope
  a = 0
  n = len(l)
  w = l[0]
  while...

func()
print(n)

Solution 3:

All the variables in your function are local, usable by that function only. Global variables are usable by all functions in the class. In your function

def func(l):
    a = 0
    n = len(l)
    w = l[0]
    while...
>>>a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

a, n, w, and l are not usable outside of the func scope. If you did something like this...

a = 0 
def func(l):
    n = len(l)
    w = l[0]
    while...

>>>a
0

I just happened to come across this read which provides you with a lot of detail on variable declaration and scope.


Solution 4:

[Python Doc the rule for local and global variables]:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. illustrate this with your example:

Use your example to illustrate, all variables declared inside the func are local variables. and even values declared outside of the function. like variable x it has no parent function but it is still actually NOT a global variable. x just get commits to memory before the func gets called

x = 5 #actually local

def func(l):
    a = 0
    n = len(l)
    w = l[0]
    print(x)  # x is local we call call it, use it to iterate but thats is pretty much it

if we try to modify the local variable x you would get an error:

x = 5
def func(l):
    a = 0
    n = len(l)
    w = l[0]
    x = x + 1 # can't do this because we are referning a variable before the funtion scope. and `x` is not global

UnboundLocalError: local variable 'x' referenced before assignment

but now if we define x as global then we can freely modify it as Python know anywhere when we call x is references to the same variable and thus the same memory address

x = 5
def func():
    global x
    x = x + 1

func()    
print(x)

it prints out : 6 for the value of x

Hope through this example you see that global variable can be accessed anywhere in the program. Whereas local variable can only be accessed within its function scope. Also, remember that even though global variables can be accessed locally, it cannot be modified locally inherently.


Solution 5:

Local Variable : When we declare a variable inside a function, it becomes a local variable. global variable : When we declare a variable outside a function , it becomes a global variable.

A python program understand difference local vs global variable

#same name for local and global variable.
a = 1         #this is global variable
def my_function():
    a = 2     #this is local variable 
    print("a= ", a)    #display local var

my_function()
print("a = ", a)      #display global var.

This program to access global variable

a = 1  #This is global var
def my_function():
    global a #This is global var. 
    print("global a= ", a)  #display new value
    a = 2   #modify global var value
    print("modify a = ", a) #display a new value

my_function()
print("global a= ", a)  #display modified value

Post a Comment for "Difference Between Local Variable And Global Variable"