Variable scope

The variable scope is an important concept to understand. Variables defined inside a function are only accessible inside the function and are called local variables. Variables defined outside a function are called global variables and are accessible anywhere in the program.


Example

message1 = "Global Variable"

def myFunction():

    |print('\nInside the function:')

    |print(message1)

    |message2 = "Local Variable"

    |print(message2)


myFunction()


print('\nOutside the function:')

print(message1)

print(message2)


Output

Inside the function:

Global Variable      

Local Variable       


Outside the function:

Global Variable

NameError: name 'message2' is not defined


Within the function, both variables are accessible. However, the local variable message2 is not accessible outside the function; therefore, we get a NameError.


The second thing to understand about variable scope is that if a local variable has the same name as a global variable, any code inside the function is accessing the local variable and any code outside of it is accessing the global variable.


Example

message1 = "dingus"

def myFunction():

    |print('\nInside the function:')

    |message2 = "dingus"

    |print(message2)


myFunction()


print('\nOutside the function:')

print(message1)


Output

Inside the function:

dingus


Outside the function:

dingus


When we print message2 (that is) inside the function, it prints "dingus" as it prints the local variable. When we print outside, it is accessing the global variable message1  and therefore also prints "dingus".

No comments:

Post a Comment