All Courses

What are local and global scope?

By Ashiqmukkil*, a year ago
  • Bookmark
0

Explain variable local and global scope

Local scope
Global scope
1 Answer
0

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

Webinars

Live Webinar on: Jobs In Data Science in 2022 and onwards.

Oct 13th (7:00 PM) 431 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More