Deal with function scope

Function scope

In addition to the global scope, each function call creates a new one:


def foo(): x = 42 
x = 1 
foo() 
print x 

The code above generates the following result.

Rebinding Global Variables

If you assign a value to a variable inside a function, it automatically becomes local unless you tell Python otherwise.


x = 1 # from   w w  w.  ja  v a  2s . c  o m
def change_global(): 
    global x 
    x = x + 1 
change_global() 
print x 

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules