World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Designed by IITians, only for AI Learners.
New to InsideAIML? Create an account
Employer? Create an account
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