Scope of Variable in Python


 Scope of variable

        All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The variable can have the same name only if they are declared in separate scope. 

The scope of variable determines the portion of  the program where you can access a particular identifier. A variable can not be used outside its scope. There are two basic scopes in Python. 

1. Global Variables

2. Local Variables

        Variables that are defined inside a function body have a local scope and those defined outside have a global scope.

 This means that local variables can be accessed inside the function in which they are declared where as global variables can be accessed through out the program body by all functions. When you call a function, the variables declared inside it are brought into scope.

Example

total=0                                          # this is a global variable

# function definition

def sum(arg1,arg2):

            total=arg1+arg2                 # here total is a local variable

            print("inside the function:",total)

            return total

# function calling

sum(10,20)

print("outside the function:",total)

Output

inside the function: 30

outside the function: 30


Note : If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables. One available in global scope (outside the function) and one available in the local scope (inside the function).

Example

x=300                                # global variable

# function definition

def myfunc():

            x=200                    # local variable

            print(x)

# function calling

myfunc()

print(x)

Output

200

300

Global Keyword

       If you need to create a global variable but are stuck in the local scope, you can use the global keyword.

The global keyword makes the variable global.

Example

# function definition

def myfunc():

            global x

            x=300

# function calling

myfunc()

print(x)

Output

300

      












No comments:

Post a Comment