If you are accessing a global variable within a function and want to change the global variable value for the rest of the program or other modules then how?

1.0K    Asked by ElayneBalding in Data Science , Asked on Jan 27, 2020
Answered by Elayne Balding

We can change a variable scope from local to global by using the "global" keyword while defining variables inside any function. See the example below:

#Declare a variable

a = 100

print(a)

#Defining a function

def local():

    global a

    a = 'Now I am changing'

    print(a)

    #Calling a function

local()

#Printing variable "a" value

print(a)

In the above example, you notice that I have used a global keyword while declaring variable “a” in “local” function, which tells the function that this is a global variable and value assigned to that variable is accessible outside that function too. This functionality helps when you are writing very huge codes and want to change the global variable value which you declared at the starting of the code.



Your Answer

Interviews

Parent Categories