Variable scope

Variable scope refers to where in a program a variable can be accessed.

Global scope

Variables made within the top level of the program, those outside of functions, are considered to have global scope. These can be accessed within any functions without having to be passed as a parameter.

def testing_the_value_of_x():
    print("The function still knows the value of x as", x)

x = 5
print("Outside the function the value of x is", x)
testing_the_value_of_x()
Outside the function the value of x is 5
The function still knows the value of x as 5

Local scope

Variables created within a function are considered to have local scope. They do not exist outside of the function in which they were created.

def testing_the_value_of_x():
    x = 10
    print("Inside the function the value of x is", x)

x = 5
print("Outside the function the value of x is", x)
testing_the_value_of_x()
print("Outside the function the value of x is still", x)
Outside the function the value of x is 5
Inside the function the value of x is 10
Outside the function the value of x is still 5

If you defined a function within another function then the scope would trickle inwards.

def testing_the_value_of_x():
    x = 10
    print("Inside the function the value of x is", x)
    def inner_function():
        y = 20
        print("The inner function still knows the value of x as", x)
        print("The inner function value of y is", y)
    inner_function()
    print("The outer function does not know the new value of y, it still has", y)

x = 5
y = 1
print("Outside the function the value of x is", x)
print("Outside the function the value of y is", y)
testing_the_value_of_x()
print("Outside the function the value of x is still", x)
Outside the function the value of x is 5
Outside the function the value of y is 1
Inside the function the value of x is 10
The inner function still knows the value of x as 10
The inner function value of y is 20
The outer function does not know the new value of y, it still has 1
Outside the function the value of x is still 5
Report a Glow concern
Cookie policy  Privacy policy

Glow Blogs uses cookies to enhance your experience on our service. By using this service or closing this message you consent to our use of those cookies. Please read our Cookie Policy.