Python - Variable scope example

Introduction

Consider the following code

Demo

# Global scope 
X = 99                # X and func assigned in module: global 
def func(Y):          # Y and Z assigned in function: locals 
    # Local scope 
    Z = X + Y         # X is a global 
    return Z 
func(1)               # func in module: result=100
# from  w  w  w  .j  a  va 2s . c om

Global names are X, func.

X is global because it's assigned at the top level of the module file.

It can be referenced inside the function as a simple unqualified variable without being declared global.

func is global and def statement assigns a function object to the name func at the top level of the module.

Local names are Y, Z

Y and Z are local to the function.

They exist only while the function runs because they are both assigned values in the function definition.

Related Topic