what is scope of variable?

Scope of variables in python


The scopes of the variables depend upon the location where the variable is being declared. The variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.

File name : index.py

  • Local variables
  • Global variables

  • Local Scope Variable.

    the variable defined inside a function is known as local scope.

    File name : index.py

    def print_message():
        message = "hello !! I am going to print a message." # the variable message is local to the function itself
        print(message)
    print_message()
    print(message) # this will cause an error since a local variable cannot be accessible here.

    Example :-

    File name : index.py

    def exfunc():
    x = 500
    print(x)

    exfunc()

    Output :-
    500

    Example :-

    File name : index.py

    def myfunc():
    x = 500
    def myinnerfunc():
    print(x)
    myinnerfunc()

    myfunc()

    Output :-
    500

    Global Scope

    The variable defined outside any function is known to have a global scope. Global variables are available from within any scope, global and local.

    A variable created outside of a function is global and can be used by everyone.

    File name : index.py

    def calculate(*args):
        sum=0
        for arg in args:
        sum = sum +arg
        print("The sum is",sum)
    sum=0
    calculate(10,20,30) #60 will be printed as the sum
    print("Value of sum outside the function:",sum) # 0 will be printed Output:

    Example :-

    File name : index.py

    x = 300

    def myfunc():
    print(x)

    myfunc()

    print(x)

    Example :-

    File name : index.py

    x = 300

    def myfunc():
    x = 200
    print(x)

    myfunc()

    print(x)
    Output :-

    200
    300

    Global Keyword :-

    If you use the global keyword, the variable belongs to the global scope.

    File name : index.py

    def myfunc():
    global x
    x = 300

    myfunc()

    print(x)

    Example :-

    To change the value of a global variable inside a function, refer to the variable by using the global keyword:

    File name : index.py

    x = 300

    def myfunc():
    global x
    x = 200

    myfunc()

    print(x)
    Output :-
    200





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here