Scope of a variable

A variable defined in one part of a program needs not to be known in other parts. All program units to which it a certain variable is known are called the scope of that variable. We first give an example; let's consider the two nested functions:

e = 3
def my_function(in1):
    a = 2 * e
    b = 3
    in1 = 5
    def other_function():
       c = a
       d = e
       return dir()
    print("""
          my_function's namespace: {} 
          other_function's namespace: {}
          """.format(dir(),other_function()))
    return a

Execution of my_function(3) results in:

my_function's namespace: ['a', 'b', 'in1', 'other_function'] 
other_function's namespace: ['a', 'c', 'd']

The variable e  is in the namespace of the program unit that encloses the function my_function . The variable ...

Get Scientific Computing with Python 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.