Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - Scope

Back


Scope

print("\n--------Scope--------\n")


def xfunc():
    x = 300   # x available only inside the function
    print(x)


xfunc()
# print(x)        # NameError: name 'x' is not defined


Local Scope


Enclosing Function Local

print("\n--------Scope: function inside function--------\n")


def xfunc():
    x = 300     # local variable
    print(x)

    def yfunc():
        print(x)    # call variable outside of yfunc()

    yfunc()    # call the function inside function


xfunc()

Global


global Keyword

print("\n--------'global' Keyword--------\n")
x = 300


def xfunc():
    x = 200


def yfunc():
    global x        # declare that x in local scope is a global variable
    x = 200


xfunc()
print(x)            # 300 global variable does not change

yfunc()
print(x)            # 200 global variable does not change

Built-in


TOP