Python scope

   Scope of a variable depends on the place, where it is defined and where it is used. Based on this, variables have categorized into following types.

  • ·       Local
  • ·       Non local
  • ·       Global

1. Local variables:

              These are the normal variables that any user use. Let, a variable t is defined inside a function.

Its scope is applicable within the function or file.

Eg:

a = 56

print(a)

Here, a is the local variable. its scope is within this program.

Next, local variable  is defined inside a function is given below.

def  its_fn():

     b = 99

     print(b)

#function call is given below.

its_fn()

while executing this program, you get the below output.


Text Box: 99

 2.Non local variables.

              When a function is defined inside the other function, this scope is used. Same variable name is used in many functions, the developer wants to differentiate it by the keyword “non local”.

#define a function its_fn() .Declare a variable ‘b’. This is the local variable.

def its_fn():

    b = 99

#Define a function  its_fn1(). Declare a nonlocal b and assign the value. call this function in its_fn() definition and return the value.

    def its_fn1():

        nonlocal b

        b = "Best wishes"

    its_fn1()

    return b

#call the its_fn() and print the value.

print(its_fn())

The output is given below.

Best Wishes

3.Global variable:

              A variable is defined and it can be used anywhere of the program. Here,the keyword is “global”

#Let a variable ‘b’ is assigned with a value 99. It is considered as local variable.

b = 99

#let a function its_fn() is defined. Here, variable ‘b’ is declared as global and assigned with 199.

def its_fn():

    global b

    b = 199

#call the function its_fn()

its_fn()

#print the value of b. it prints the global variable value.

print(b)


So, the output is

 Text Box: 199

 These are the various types of variables used in python and its scope is explained with examples.

No comments:

Post a Comment