Explain Scopes in Python?

By Rama, 2 months ago
  • Bookmark
0

Explain different scopes in python

Scope
Python
1 Answer
0

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


Global Scope

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


Function Inside Function

The local variable can be accessed from a function within the function


def func():
     no = 100
     def innerfunc():
            print(no)
     innerfunc()

func()
100


Naming Variables

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


Using Global Keyword

Use the global keyword, the variable belongs to the global scope

def func():
    global no
    no = 100
  
func()
  
print(no)

100




Your Answer

Webinars

How To Land a Job in Data Science

Jun 24th (7:00 PM) 238 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More