Thursday, October 25, 2018

Python Ninja Bootcamp 24-Scope (Local ,Enclosing Global ,Build-in)

Learn Python like a Professional! Take You from 0 to Hero




In this Python lecture, we will learn about the Scope.

"Scope refers to the place where we access the variable."


Type of Scope

1. 'Local' are variables define within the function.
2. 'Enclosing' are variable in the local scope of enclosing functions.  

3. 'Global' are variables defined at the top level of the script or declared by using global keyword.

4. 'Built-in' are names that are predefined in the python.


Let's look at example-


Local & Global

a = 'global a'

def check():
    b = 'local b'
    print(b)
    
check()
>> local a
a = 'global a'

def check():
    b = 'local b'
    print(a)   
check()
>>global a

a = 'global a'

def check():
    b = 'local b'
    print(a) 
check()

print(b)
>>global a
>>NameError : name 'b' is not defined outside


a = 'global a'

def check():
    b = 'local b'
    print(a)       
check()

print(a)
>>global a
>>global a

a = 'global a'

def check():
    a = 'local a'
    print(a)        
check()

print(a)
>>local a
>>global a

def check():
    global a
    a = 'local a'
    print(a) 
check()

print(a)
>> local a
>> local a

def check():
    a = 'local a'
    print(a)     
check()

print(a)
>> local a
>>>>NameError : name 'a' is not defined outside


Enclosing Scope


def outer():

    a='outer a'
    
    def inner():
        a='inner a'
        print(a)   
    inner()
    
    print(a)
    
outer()
>>inner a
>>outer a


def outer():

    a='outer a'
    
    def inner():
        #a='inner a'
        print(a)
        
    inner()
    
    print(a)
    
outer()
>>outer a
>>outer a

Built-in

len([1,2,3,4,5])
>> 5

def len():
    print('User define len()')

len()

len(list([1,2,3,4,5]))
>>User define len( )
>>TypeError: len() takes 0 positional arguments but 1 was given
Be very while working with Built-in and user define function.


EDITS ARE WELCOMED!!

In the next Blog, we will discuss Q&A 3rd 

https://sngurukuls247.blogspot.com/2018/10/python-ninja-bootcamp-25-q-third.html

......................................................................................................................................

Follow the link below to access Free Python Lectures-
https://www.youtube.com/channel/UCENc9qI7_r8KMf6-_1R1xnw

Instagram-
https://www.instagram.com/python.india/

View the Jupyter Notebook for this lecture

Download the Jupyter Notebook for this lecture 



Feel free contact me on-

1 comment: