Wednesday, July 3, 2019

Example - global keyword

You can declare a global variable in python easily enough but when you try to change it from a function no error is displayed and the old value is still there.

#declare a global variable
a = 23

def print_a_variable():
    print(a) #Printing it works just fine


def change_a_variable():
    a = 100000
    print(a) #seems to work but a is actually a new variable


print_a_variable()
change_a_variable()
print(a)

Output:
23
100000
23

If you use the keyword global in your function then the global is no longer read-only.


#declare a global variable
a = 23

def print_a_variable():
    #global a - not needed here because we can have readonly access to globals
    print(a) #Printing a works just fine


def change_a_variable():
    global a #If you want to change the global then it has to be declared here
    a = 100000
    print(a) #a is declared local and doesn't effect the global variable a


print_a_variable()
change_a_variable()
print(a) #a is still 23

Output:
23
100000
100000

No comments:

Post a Comment

nonlocal keyword

The nonlocal keyword is used to allow an inner function to access variables defined in an outer function. Without using the nonlocal keywo...