What are local and global scope?

By Ashiqmukkil*, 8 months ago
  • Bookmark

Explain variable local and global scope

Local scope
Global scope
1 Answer

All Python variables which are accessible at some point in code are either in local scope or in global scope.

The explanation is that local scope includes all variables defined in the current function and global scope includes

variables defined outside of the current function.

foo = 1 # global

def func():
    bar = 2 # local
    print(foo) # prints variable foo from global scope
    print(bar) # prints variable bar from local scope

One can inspect which variables are in which scope. Built-in functions locals() and globals() return the whole

scopes as dictionaries.

foo = 1

def func():
    bar = 2
    print(globals().keys()) # prints all variable names in global scope
    print(locals().keys()) # prints all variable names in local scope

Your Answer


Live Masterclass on : "How Machine Learns in Machine Learning"

Dec 9th (6:00 PM) 228 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More