World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITian's, only for AI Learners.
Explain different scopes in python
Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows:
Local Scope :
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function
def func(): no = 100 print(no) func() 100
A global scope refers to the objects available throught the code execution since their inception.
no = 100 def func(): print(x) func() print(x) 100 100
The local variable can be accessed from a function within the function
def func(): no = 100 def innerfunc(): print(no) innerfunc() func() 100
Same variable name inside and outside of a function, Python will consider them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function):
no = 100 def func(): no = 200 print(no) func() print(no) 200 100
Use the global keyword, the variable belongs to the global scope
def func(): global no no = 100 func() print(no) 100