All Courses

What are local and global scope?

By Ashiqmukkil*, 2 years 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


How To Land a Job in Data Science?

Feb 9th (7:00 PM) 184 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More