Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

global keyword python

# When we create a variable inside a fxn, it is local by default.
# When we define a variable outside of a fxn, it is global by default. You don't have to use global keyword.
# We use global keyword to read and write a global variable inside a function.
# Use of global keyword outside a function has no effect.

#can access a global variable inside a fxn... but cannot modify it (see next)
c = 1 # global variable
def add():
    print(c)
add()           #1

# cannot modify a global variable from inside a fxn
c = 1 # global variable
def add():
    c = c + 2 # increment c by 2
    print(c)
add()       #UnboundLocalError: local variable 'c' referenced before assignment

# declare global keyword, allows fxn to modify global variable
c = 0 # global variable
def add():
    global c
    c = c + 2 # increment by 2
    print("Inside add():", c)
add()
print("In main:", c)
# Inside add(): 2
# In main: 2

# Global in nested function 
# Declared a global variable inside the nested function bar(). 
# Inside foo() function, x has no effect of the global keyword.
# Before and after calling bar(), the variable x takes the value of local variable i.e x = 20
# Outside of the foo() fxn, the variable x will take value defined in the bar() fxn i.e x = 25
def foo():
    x = 20

    def bar():
        global x
        x = 25
    
    print("Before calling bar: ", x)
    print("Calling bar now")
    bar()
    print("After calling bar: ", x)

foo()
print("x in main: ", x)

# Before calling bar:  20
# Calling bar now
# After calling bar:  20
# x in main:  25

# declare global variable in local scope
artist = "Michael Jackson"

def printer(artist): 
    global internal_var                     #declare global variable within fxn
    internal_var= "Whitney Houston"
    print(artist,"is an artist")

printer(artist) 
printer(internal_var)

# Michael Jackson is an artist
# Whitney Houston is an artist
Source by www.programiz.com #
 
PREVIOUS NEXT
Tagged: #global #keyword #python
ADD COMMENT
Topic
Name
8+9 =